'Forbidden Request while requesting POST from Axios
I got a forbidden request when sending a POST request using axios.
Here is my axios function:
const headers = {
'Authorization': `bearer ${JSON.parse(localStorage.getItem('TOKEN'))}`,
'Content-Type': 'application/json'
}
const getByRelationCode = (data) => {
const response = Client.post(`${TRACKING_API}/getByRelationCode`, data, {
headers
})
return response
}
And this is the calling function
const getDocument = (relationCode) => {
await Service.getByRelationCode({ relationCode })
.then((res) => {console.log(res))
.catch(err => console.log(err))
}
When I hit the endpoint using postman, the endpoint returned the response. But when i call it using Axios it returns a forbidden request. Is there missing from my code?
Solution 1:[1]
You have miss spelled on your header.
const headers = {
'Authorization': `Bearer ${JSON.parse(localStorage.getItem('TOKEN'))}`,
'Content-Type': 'application/json'
}
But in some framework we can customize it. If you have customized it for your own then you can call it as bearer. Though it's not correct to name it like that way.
Solution 2:[2]
try like this
const config = {
headers: {
'Authorization': `bearer ${localStorage.getItem('TOKEN')}`,
'Content-Type': 'application/json' }
};
const getByRelationCode = (data) => {
const response = Client.post(`${TRACKING_API}/getByRelationCode`, data, config)
return response;
}
Solution 3:[3]
I think it is happening because you spelled Bearer wrong in your code and the server getting your request but is not able to extract the token from it.
Try it with the correct spelling of Bearer.
const headers = {
'Authorization': `Bearer ${JSON.parse(localStorage.getItem('TOKEN'))}`,
'Content-Type': 'application/json'
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karthikeyan |
| Solution 2 | Mohammad Ali Rony |
| Solution 3 | Dharmik Patel |
