Ad

Auth Error With POST Request: "Authentication Credentials Were Not Provided" Using Axios, But Works Using POSTMAN

- 1 answer

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
            }
        })

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

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

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...?

Ad

Answer

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

So you need to use like this:

  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}`
      }
    }
  );

Docs:

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

Ad
source: stackoverflow.com
Ad