Reputation: 69
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);
}
};
Upvotes: 5
Views: 4122
Reputation: 46191
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 */},
});
Upvotes: 5
Reputation: 234
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);
}
};
Upvotes: -1