Always getting 401 (Unauthorized) error with axios. post or get

Hello,
I’ve got a problem. On application (React) I have register and login pages, they were working fine before, but I updated my nodejs and also created new strapi project, made all same settings as my previous one, and now everytime I try using axios.post to register or login, i get error xhr.js:177 POST http://localhost:1338/auth/local 401 (Unauthorized) or same error but GET. To be more precise Here’s error and message:

error: "Unauthorized"
message: "Invalid token."

Why there’s even token mentioned? I’m registering and logging in, I don’t need token.
Here’s my code to login page.

axios
.post('http://localhost:1338/auth/local', {
identifier: this.state.userName,
password: this.state.userPassword
 })
.then(response => {
// Handle success.
console.log('Well done!');
login(response.data.jwt);
})
.catch(error => {
// Handle error.
console.log('An error occurred:', error.response);
});

Also, I’m using 1338 port, so that’s not the case. Also with Postman it works fine, I can register and login, everything…

2 Likes

You get this error about the invalid token because your request also sends an authorization header with the token.

If you open Developer tools, go to the network tab, repeat the login/register request, you will notice that in Requests Headers section of this request, there is an Authorization: Bearer {token} header. To solve this just delete the cookies/local storage from your localhost. Axios by default adds all the cookies to your requests, so

Hello,
Thank you for reply, I checked network tab, headers as you suggested, I can see that Request Header contains this: Authorization: Bearer null So that messes with my project? And how exactly should I clear cookies and localstorage? On chrome I cannot see any cookies on my localhost and what about localstorage. I should clear them with javascript within react?

did you resolved this error. i get same error from nowhere when im tryign to logging the user