Taylan Gurel
Taylan Gurel

Reputation: 37

Axios Post method authorization does not work - React

I am developing a website [using React for front-end // Spring for backend] and in this website there is an admin panel. There is a button which lets other admins to add users to the database but I have a problem with axios' post method.

I checked so many different sources but couldnt find exactly what I am looking for. So here I am.

I get this error, 401 error code, unauthorized client, when using this syntax below

async addUsers(newData){

        const headers = {
            'Content-Type': 'application/json',
            'Authorization': window.$auth
          }

        await Axios.post(
            "http://localhost:8080/admin/addUser",  
            JSON.stringify(newData),  
            {headers: headers}
            );
    }


Before, I tried using a different syntax which I think is wrong, and with this syntax I get 415 error code: 415 error code, unsupported media type

async addUsers(newData){

        await Axios.post(
            "http://localhost:8080/admin/addUser",  
            JSON.stringify(newData),  
            {auth:window.$auth},
            {headers: {'Content-Type':'application/json'}}
            );
    }

P.S: I tried to add User manually to database using Insomnia REST client and it successfully adds it and returns 200 Code.
Could someone help me with this problem, please?

Upvotes: 0

Views: 1420

Answers (2)

Taylan Gurel
Taylan Gurel

Reputation: 37

It looks like this "authorization always returning 401 error code" was a known issue. Changing the complete syntax fixed it. Here is the site that I found the solution on https://github.com/axios/axios/issues/926
Here is the part of my code which that I fixed and now works:

async addUsers(newData){

        await Axios({
            method:'post',
            url:'http://localhost:8080/admin/addUser',
            data:JSON.stringify(newData),
            auth:window.$auth,
            headers:{'Content-Type':'application/json'}
        })
    } 

Upvotes: 1

iamwebkalakaar
iamwebkalakaar

Reputation: 358

Instead of sending authorization token with each request better add it as a default header. First check if token exist if it is exist add it

if(authorization_token){
 axios.defaults.headers.common['Authorization'] = authorization_token;
}

Upvotes: 2

Related Questions