315

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?

2
  • I don't think its an axios issue at all. check your validToken() function, it returning somthing that your server does not understand. Dec 6, 2016 at 5:40
  • I double checked the function and also used the token string here instead of the function,, still the same
    – rakibtg
    Dec 6, 2016 at 6:23

18 Answers 18

379
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.

10
  • 11
    You missed a space between bearer and token - then it will work.
    – dec
    Mar 14, 2018 at 8:27
  • Doctor's post: "key: "value" has a quote that should be removed... But fixing that did get the auth to work for my react-native app.
    – mediaguru
    Jun 16, 2018 at 3:51
  • 1
    @mediaguru Thx for the comment. I fixed it (I suppose) ! The quote must have been introduce by someone editing the answer...
    – Doctor
    Jun 18, 2018 at 7:11
  • 4
    Bearer should be used with capital B, shouldn't it? May 30, 2019 at 12:00
  • 1
    @Alizadeh118 Yes, according to the HTTP spec. But many api's don't insist on the correct capitalization. Feb 27, 2020 at 2:55
177

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;

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.

8
  • 44
    Bearer needs to be capitalised for some APIs (I discovered the hard way). Mar 18, 2019 at 14:05
  • 2
    This should be accepted answer. This is better approach. Oct 30, 2020 at 9:41
  • 3
    @FaizanMubasher not if yo use different servers
    – Musculaa
    Aug 3, 2021 at 14:10
  • 1
    for loading token from a function or local storage we need interceptors Aug 7, 2021 at 10:32
  • 1
    The spec says to always use "Bearer" with a capitol B. rfc-editor.org/rfc/rfc6750
    – Todd Smith
    May 11 at 5:14
61

You can create config once and use it everywhere.

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

instance.get('/path')
.then(response => {
    return response.data;
})
6
  • Where is the value of token passed from in this example? For my application, the token would be passed back to the api either in the header or body after a successful login.
    – Ken
    Nov 15, 2018 at 3:58
  • its here headers: {'Authorization': 'Bearer '+token} Mar 31, 2019 at 7:47
  • How to pass data if it is an POST request Mar 31, 2019 at 7:58
  • 1
    For those who are wondering from where the value of token can be passed, here is es6 syntax - const instance = (token) => axios.create({ baseURL: `${config.API_URL}`, timeout: 1000, headers :{ 'authorization': 'Bearer ' + token } })
    – Jeet
    Jun 22, 2020 at 17:35
  • instance.get('/path') .then(response => { return response.data; }) What is path ??
    – ZebraCoder
    Jun 21, 2022 at 11:09
34

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);
  }
);
7
  • 2
    Is this the community standard for configuring the headers with axios? Sep 28, 2019 at 16:26
  • 2
    @5ervant I had a really ugly time using this approach. It was a lot of pain and I so don't recommend it.
    – ankush981
    May 15, 2020 at 16:59
  • @ankush981 what is so bad about this approach and which one do u recommend? Jun 3, 2020 at 0:18
  • 2
    @NenadKaevik There's a particular use case I was trying to cover (response interception): letting the user know when the server says 403 in response. People generally put the token verification step during component load, but suppose your token was invalidated a few seconds after it was verified (for whatever reason). Now when the person clicks a button, I'd like them to know they've been signed out. It's hard to do this using interceptors as they add global behavior. I got into a reload loop because the request interceptor would always add the token and the response interceptor would redirect
    – ankush981
    Jun 4, 2020 at 6:49
  • @NenadKaevik So, maybe the flow was hard to achieve or I was using the wrong approach, but since then I kind of started hating interceptors.
    – ankush981
    Jun 4, 2020 at 6:49
33

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

0
17

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)
});
0
11

Just in case someone faced the same issue.

The issue here is when passing the header without data, the header's configuration will be in the payload data, So I needed to pass null instead of data then set the header's configuration.

const config = {
         headers: {
             "Content-type": "application/json",
              "Authorization": `Bearer ${Cookies.get("jwt")}`,
         },
    };    
axios.get(`${BASE_URL}`, null, config)
10

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",

2
  • I don't know why but with this way it's doesn't work on Safari on iOS device :(
    – ZecKa
    Dec 12, 2019 at 9:05
  • nice simple method for me
    – D2TheC
    Oct 1, 2020 at 12:49
5

I use a separate file to init axios instance and at the same time, I add intercepters to it. Then in each call, the intercepter will add the token to the request header for me.

import axios from 'axios';
import { getToken } from '../hooks/useToken';

const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
});

axiosInstance.interceptors.request.use(
  (config) => {
    const token = getToken();
    const auth = token ? `Bearer ${token}` : '';
    config.headers.common['Authorization'] = auth;
    return config;
  },
  (error) => Promise.reject(error),
);

export default axiosInstance;

Here is how I use it in the service file.

import { CancelToken } from 'axios';
import { ToolResponse } from '../types/Tool';
import axiosInstance from './axios';

export const getTools = (cancelToken: CancelToken): Promise<ToolResponse> => {
  return axiosInstance.get('tool', { cancelToken });
};

1
  • Clear solution. can you give ToolResponse file example. Thank you.
    – Kvlknctk
    Oct 21, 2021 at 19:07
1

// usetoken is hook i mad it

export const useToken = () => {
     return JSON.parse(localStorage.getItem('user')).token || ''
}
const token = useToken();



const axiosIntance = axios.create({
    baseURL: api,
    headers: {
        'Authorization':`Bearer ${token}`
    }
});

axiosIntance.interceptors.request.use((req) => {
    if(token){
        req.headers.Authorization = `Bearer ${token}`;
    }
    return req;
})
1

If you are sending a post request with empty data remember to always set the second parameter to either empty object or empty string just as in the example below. e.g: axios.post('your-end-point-url-here', '', config)

if you don't set it axios will assume that whatever you are passing as the second parameter is a formData

const config = {
      headers: { Authorization: `Bearer ${storage.getToken()}` }
    };
    axios
      .post('http://localhost:8000/api/v1/get_token_payloads', {}, config)
      .then(({ data: isData }) => {
        console.log(isData);
      })
      .catch(error => {
        console.log(error);
      });
1

You must mention the 2nd parameter body for the post request even if it is empty, try this :

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

You can try configuring the header like this:

const headers = {"Content-Type": "text/plain", "x-access-token": token}

0

try one of these✅:

pass an empty object/payload as a second parameter to Axios.post

axios.post(
'/api/user/get-user-info-by-id',  //first paramater
{},                               //pass empty object to second paramater
{
        headers: {
          Authorization: "Bearer "+ localStorage.getItem("token"),
        }
      })

or pass a null

axios.post('/api/user/get-user-info-by-id',null, {
        headers: {
          Authorization: "Bearer "+ localStorage.getItem("token"),
        }
      })
0

I used like this - Get API

      axios({
        method: "get",
        url: `api`,
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      }).then((res) => {
        const data = res?.data;
        if (data?.isSuccess) {
         console.log("data>>>>>>",data)
        } else {
          console.log(data?.errorMessage);
        }
      });

Post API

    axios({
      method: "post",
      url: "api",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      data: {
        name: "name",
        email: "email",
      },
    }).then((res) => {
      const data = res.data;
     if (data?.isSuccess) {
         console.log("data>>>>>>",data)
        } else {
          console.log(data?.errorMessage);
        }
    });

-2

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

-2

there are a lot of good solution but I use this

let token=localStorage.getItem("token");

var myAxios=axios.create({
  baseURL: 'https://localhost:5001',
  timeout: 700,
  headers: {'Authorization': `bearer ${token}`}
});

export default myAxios;

then i import myaxios to my file and

myAxios.get("sth")
-2

You can use interceptors in axios:


axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

More on that you can find here: https://axios-http.com/docs/interceptors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.