POST 请求的身份验证错误:“未提供身份验证凭据"使用 Axios,但使用 POSTMAN身份验证、凭据、错误、POST

2023-09-07 11:12:55 作者:空欢喜

我正在使用 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

 
精彩推荐