5

I've been fetching some data from a private API with axios, but now I'm having a problem fetching data from one specific endpoint.

The interesting thing is that with the built in fetch API, I'm receiving 200 response, but the identical request with axios keeps retuning 401 error. Any idea what can be the problem?

This code works:

const upVoteCommentTwo = async () => { console.log(localStorage.getItem("access_token")); try { const response = await fetch( `https://exammple.com/comments/${commentId}/vote/up`, { method: "POST", headers: { "X-API-KEY": "XXX", "Authorization": localStorage.getItem("access_token"), }, } ); console.log(await response.status); } catch (err) { console.log(err); } }; 

And this does not work:

const upVoteCommentOne = async () => { console.log(localStorage.getItem("access_token")); try { const response = await axios.post( `https://example.com/comments/${commentId}/vote/up/`, { headers: { "Content-Type": "application/json", "X-API-KEY": "XXX", "Authorization": localStorage.getItem("access_token"), }, } ); console.log(response.status); } catch (err) { console.log(err); } }; 
0

2 Answers 2

5

The problem is coming from axios's parameters. One valid way, according to the doc and that seems to be working for most people according to this issue on GitHub is to call it like below, with an object:

const response = await axios({ method: "post", url: `https://example.com/comments/${commentId}/vote/up/`, headers: { "Content-Type": "application/json", "X-API-KEY": "XXX", "Authorization": localStorage.getItem("access_token"), }, data: {/* Your Data Goes Here */}, }); 
Sign up to request clarification or add additional context in comments.

Comments

-1
const upVoteCommentOne = async () => { console.log(localStorage.getItem("access_token")); try { const response = await axios.post( `https://example.com/comments/${commentId}/vote/up/`, { //body:...if any } headers: { "X-API-KEY": "XXX", "Authorization": localStorage.getItem("access_token"), }, } ); console.log(response.status); } catch (err) { console.log(err); } }; 

1 Comment

pls explain. Just catch the error doesn't mean if helps OP

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.