Home > Software design >  Forbidden Request while requesting POST from Axios
Forbidden Request while requesting POST from Axios

Time:05-17

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?

CodePudding user response:

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;
}

CodePudding user response:

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'
}

CodePudding user response:

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.

  • Related