Home > Software design >  Getting errors in axios post method
Getting errors in axios post method

Time:05-22

I simply can't manage to understand what is wrong with this code. I'm trying to make a post request to logout from an API using axios. I keep getting error 401 which I believe that it is because the request isn't using the right code, but I already tried it with Authorization, bearer, token, etc. and nothing works.

const handleExit = () => {
    const tokenAtual = sessionStorage.getItem("token");
    
    console.log(tokenAtual)

    axios.post("https://api.secureme.pt/api/v1/auth/logout", {
        headers: {
            'Authorization': `token ${tokenAtual}`
          }
    }).then(response =>{
        setLoading(false);
        console.log("response.data.message>>>>>>>>>>>" , response.data.message);
        navigate('/')
    }).catch(error => {
        console.log("error -> ", error);
        setLoading(false);
        if(error.response.status === 406){
            setError(error.response.data.message);
        }
        else {
            setError("Something went wrong, please try again later.");
        }
        console.log("error -> ", error);
    });
    

}

------------Postman code-----------

curl --location --request POST 'https://api.secureme.pt/api/v1/auth/logout' \
--header 'Authorization: ----tokenAtual----'

CodePudding user response:

In the axios.post method :-

axios.post(url[, data[, config]])

The first parameter is url. Second parameter is data and the third parameter is config. You are passing config in place of data.

Here is the fixed form:

axios.post('https://api.secureme.pt/api/v1/auth/logout', undefined, {headers: {
  'Authorization': tokenAtual
}})

CodePudding user response:

The issue with your request is with syntax/params you are sending to post req it should like

axios.post(
"https://api.secureme.pt/api/v1/auth/logout",
{},
{
headers:{
'Authorization': `token ${tokenAtual}`
}
})

The syntax/param for the post request is

(url: string, data?: any, config?: AxiosRequestConfig | undefined)

So you are trying to send config in place of data

  • Related