POST 请求的身份验证错误:“未提供身份验证凭据"使用 Axios,但使用 POSTMAN [英] Auth error with POST request: "Authentication credentials were not provided" using Axios, but works using POSTMAN

查看:39
本文介绍了POST 请求的身份验证错误:“未提供身份验证凭据"使用 Axios,但使用 POSTMAN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React 并尝试处理用户更改密码.我正在发送这样的 POST 请求:

I'm using React and trying to handle password change by the user. I'm sending a POST request like this:

axios.post('http://127.0.0.1:8000/users/password/change/', {
            headers: {
                'Content-type': 'application/json',
                'Authorization': `Token ${token}`
            },
            data: {
                new_password1: newPassword1,
                new_password2: newPassword2
            }
        })

...我收到 401 错误:未提供身份验证凭据".

...and I get a 401 error: "Authentication credentials were not provided".

但是,如果我通过 POSTMAN 发送完全相同的相同请求,它就可以正常工作.

However, if I send the exact same request via POSTMAN, it works fine.

我也在同一个应用中做 GET 请求来获取用户数据,它也可以正常工作:

I am also doing GET request in the same app to get user data, and it also works without any problem:

axios.get('http://127.0.0.1:8000/users/' + path + '/' + userId + '/', {
            headers: {
                'Content-type': 'application/json',
                'Authorization': `Token ${token}`
            }
        })

可能是什么问题...?

What could be the issue...?

推荐答案

axios.post 期望(url、data、config).

axios.post expects (url, data, config).

所以你需要这样使用:

  axios.post(
    "http://127.0.0.1:8000/users/password/change/",
    {
      new_password1: newPassword1,
      new_password2: newPassword2
    },
    {
      headers: {
        "Content-type": "application/json",
        "Authorization": `Token ${token}`
      }
    }
  );

文档:

https://github.com/axios/axios#axiosposturl-data-config

这篇关于POST 请求的身份验证错误:“未提供身份验证凭据"使用 Axios,但使用 POSTMAN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆