Sending the bearer token with axios

rakibtg picture rakibtg · Dec 6, 2016 · Viewed 210.7k times · Source

In my react app i am using axios to perform the REST api requests.

But it's unable to send the Authorization header with the request.

Here is my code:

tokenPayload() {
  let config = {
    headers: {
      'Authorization': 'Bearer ' + validToken()
    }
  }
  Axios.post( 
      'http://localhost:8000/api/v1/get_token_payloads',
      config
    )
    .then( ( response ) => {
      console.log( response )
    } )
    .catch()
}

Here the validToken() method would simply return the token from browser storage.

All requests are having a 500 error response saying that

The token could not be parsed from the request

from the back-end.

How to send the authorization header with each requests? Would you recommend any other module with react?

Answer

Doctor picture Doctor · Mar 18, 2017
const config = {
    headers: { Authorization: `Bearer ${token}` }
};

const bodyParameters = {
   key: "value"
};

Axios.post( 
  'http://localhost:8000/api/v1/get_token_payloads',
  bodyParameters,
  config
).then(console.log).catch(console.log);

The first parameter is the URL.
The second is the JSON body that will be sent along your request.
The third parameter are the headers (among other things). Which is JSON as well.