I am trying to make an api call using axios , if i use the put,post or delete method then i am able to pass bearer token in the header , but no in the get method
const config = { headers: { Authorization: `Bearer ${token}` } };
this get request doesn’t work
axios.get(
"http://localhost:3001/api/message/",
{
chatId: "661925ba21df3cb3dc4958be",
},
config
)
.then(async (results) => {
console.log(results);
})
.catch((error) => {
console.log(error);
});
axios.post(
"http://localhost:3001/api/message/",
{
chatId: "661925ba21df3cb3dc4958be",
},
config
)
.then(async (results) => {
console.log(results);
})
.catch((error) => {
console.log(error);
});
I just changed get to post and the bearer token is included in the header , what’s the issue with get method?
2
Answers
The sytax of axios.get / axios.post is different:
BTW, you can use interceptos to make it easier:
You are calling the request wrongly, you call the
axios.get()
request slightly different from how you doaxois.post()
axios.get(url, config)
take the API URL as the first parameter and the config as the second parameter since you can’t ideally send abody
with aget
request when it comes tohttps
unlike inpost
whereaxios.post(url,body,config)
where the first parameter is theurl
, second is therequest body
and third is theconfig
Update your code like this:
If you need to pass data in a
get
request you can do that in the query parameter like this