[reactjs] Sending the bearer token with axios

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?

This question is related to reactjs rest token axios access-token

The answer is


By using Axios interceptor:

const service = axios.create({
  timeout: 20000 // request timeout
});

// request interceptor

service.interceptors.request.use(
  config => {
    // Do something before request is sent

    config.headers["Authorization"] = "bearer " + getToken();
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

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.


You can create config once and use it everywhere.

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'Authorization': 'Bearer '+token}
});

instance.get('/path')
.then(response => {
    return response.data;
})

Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;

Edit, Thanks to Jason Norwood-Young.

Some API require bearer to be written as Bearer, so you can do:

axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}

Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.


axios by itself comes with two useful "methods" the interceptors that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request.

I made apackage that helps you out:

$ npm i axios-es6-class

Now you can use axios as class

export class UserApi extends Api {
    constructor (config) {
        super(config);

        // this middleware is been called right before the http request is made.
        this.interceptors.request.use(param => {
            return {
                ...param,
                defaults: {
                    headers: {
                        ...param.headers,
                        "Authorization": `Bearer ${this.getToken()}`
                    },
                }
            }
        });

      this.login = this.login.bind(this);
      this.getSome = this.getSome.bind(this);
   }

   login (credentials) {
      return this.post("/end-point", {...credentials})
      .then(response => this.setToken(response.data))
      .catch(this.error);
   }


   getSome () {
      return this.get("/end-point")
      .then(this.success)
      .catch(this.error);
   }
}

I mean the implementation of the middleware depends on you, or if you prefer to create your own axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a it is the medium post where it came from


The second parameter of axios.post is data (not config). config is the third parameter. Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config


This works and I need to set the token only once in my app.js:

axios.defaults.headers.common = {
    'Authorization': 'Bearer ' + token
};

Then I can make requests in my components without setting the header again.

"axios": "^0.19.0",


Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to token

Sending the bearer token with axios JWT (JSON Web Token) library for Java Python requests library how to pass Authorization header with single token best practice to generate random token for forgot password syntax error: unexpected token < What is the difference between a token and a lexeme? how to generate a unique token which expires after 24 hours? Parse (split) a string in C++ using string delimiter (standard C++) How do I fix a "Expected Primary-expression before ')' token" error? How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

Examples related to axios

How to post query parameters with Axios? Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check How can I add raw data body to an axios request? Axios Delete request with body and headers? Axios having CORS issue Axios handling errors Returning data from Axios API axios post request to send form data Change the default base url for axios Access Control Origin Header error using Axios in React Web throwing error in Chrome

Examples related to access-token

Sending the bearer token with axios Basic HTTP and Bearer Token Authentication python request with authentication (access_token) Not receiving Google OAuth refresh token How to refresh token with Google API client? Get refresh token google api Facebook Access Token for Pages facebook Uncaught OAuthException: An active access token must be used to query information about the current user Why Does OAuth v2 Have Both Access and Refresh Tokens?