Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios post unauthorized error yet curl works

Trying to hit YouTrack's API via axios but I am receiving an unauthorized error, while same params via curl work.

curl:

curl -X GET \
'https://<my youtrack url>/api/issues' \
-H 'Authorization: Bearer perm:<my token>' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json'

axios:

const config = {
    headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer perm:<my token>'
    },
    responseType: 'json',
};

axios.get('https://<my youtrack url>/api/issues', {}, config)
    .then((response) => {
        console.log(response.data);
    })
    .catch(e => {
        console.log('Error: ', e.response.data)
    });

The curl correctly returns JSON of my available issues, whereas my axios call returns an error

{error: "Unauthorized", error_description: ""}

Thanks

like image 759
Arthur Avatar asked Feb 05 '19 13:02

Arthur


People also ask

How does Axios post () work?

So the axios.post () does work, the endpoint it calls does get hit and the data is sent, the task is performed and then the endpoint returns an Ok (200) result. But I still get this error which the catch block catches and without a solution this means that I'll never be able to run something within the .then () block.

How do I send custom headers from Axios?

If you want to send custom headers, the go into the third parameter of axios.post. That may although not be a problem, as axios will set the correct content-type header automatically. Second, have you debugged your server if it correctly interprets the sent data?

What is missing in the mix between Axios and Cors?

However the one thing missing in the mix was {crossdomain : true }. Axios - axios ( {withCredentials : true, crossdomain : true, .. other options .. }) Server (in case running on express) -- app.use (cors ( {credentials : true, origin : ['your domain where axios is running']}))

Does Axios randomly create JWT tokens and add them?

No axios does not randomly create jwt tokens and add them to requests, unless you speficially tell it to do so. When you say you recreated the server component, check if you recreated the data correctly. Check what the requesthandler at the server does with this data.


1 Answers

Send the config as the second parameter, as GET requests don't need the body

axios.get('https://<my youtrack url>/api/issues', config)
    .then((response) => {
        console.log(response.data);
    })
    .catch(e => {
        console.log('Error: ', e.response.data)
    });
like image 97
Dalvtor Avatar answered Oct 19 '22 20:10

Dalvtor