309

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?

Ilyas karim
  • 4,592
  • 4
  • 33
  • 47
rakibtg
  • 5,521
  • 11
  • 50
  • 73
  • I don't think its an `axios` issue at all. check your `validToken()` function, it returning somthing that your server does not understand. – xiaofan2406 Dec 06 '16 at 05:40
  • I double checked the function and also used the token string here instead of the function,, still the same – rakibtg Dec 06 '16 at 06:23

18 Answers18

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

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
Doctor
  • 7,115
  • 4
  • 37
  • 55
  • 11
    You missed a space between bearer and token - then it will work. – dec Mar 14 '18 at 08: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 '18 at 03: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 '18 at 07:11
  • 4
    `Bearer` should be used with capital B, shouldn't it? – Alizadeh118 May 30 '19 at 12:00
  • @Alizadeh118 It seems to be working with and without any capital letters :-) – Doctor Jun 03 '19 at 10:33
  • 1
    @Alizadeh118 Yes, according to the HTTP spec. But many api's don't insist on the correct capitalization. – OneHoopyFrood Feb 27 '20 at 02:55
  • For some `API's` you might need to add `/` at the end of the endpoint. For example, instead of `http://localhost:8000/api/v1/get_token_payloads` should be `http://localhost:8000/api/v1/get_token_payloads/`. – Daniel Danielecki Jun 30 '21 at 18:26
  • I would like to add the definition of the axios post request to follow up correctly each call https://github.com/axios/axios/blob/e9965bfafc82d8b42765705061b9ebe2d5532493/index.d.ts#L151 – pmiranda Jul 02 '21 at 16:06
  • Anyone else upvoting for the clever usage of console.log as param? – Nicolas Durán Oct 06 '21 at 01:47
  • @NicolasDurán Not me for one... I hate it when people just edit my answers. I don't even get notified. Even if the console.log() is better i didn't test it. So I can't vouch for the quality anymore. – Doctor Oct 06 '21 at 18:23
175

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.

ブルック
  • 15
  • 1
  • 5
Ilyas karim
  • 4,592
  • 4
  • 33
  • 47
59

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;
})
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Sarvar Nishonboyev
  • 12,262
  • 10
  • 69
  • 70
  • 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 '18 at 03:58
  • its here `headers: {'Authorization': 'Bearer '+token}` – M.suleman Khan Mar 31 '19 at 07:47
  • How to pass data if it is an POST request – M.suleman Khan Mar 31 '19 at 07: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 '20 at 17:35
  • instance.get('/path') .then(response => { return response.data; }) What is path ?? – ZebraCoder Jun 21 '22 at 11:09
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

Nick Uraltsev
  • 24,607
  • 4
  • 25
  • 14
33

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);
  }
);
Ilyas karim
  • 4,592
  • 4
  • 33
  • 47
aneesh
  • 431
  • 4
  • 5
  • 2
    **Is this the community standard for configuring the headers with axios?** – 5ervant - techintel.github.io Sep 28 '19 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 '20 at 16:59
  • @ankush981 what is so bad about this approach and which one do u recommend? – Nenad Kaevik Jun 03 '20 at 00: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 04 '20 at 06: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 04 '20 at 06:49
  • @ankush981 You are damn right about this... Thanks for the explanation brudda :) – Nenad Kaevik Jun 04 '20 at 11:31
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)
});
Neel Patel
  • 2,028
  • 18
  • 17
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)
Hasan Zahran
  • 1,364
  • 16
  • 14
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",

gdfgdfg
  • 3,181
  • 7
  • 37
  • 83
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

// 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;
})
Mohammed Al-Reai
  • 2,344
  • 14
  • 18
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);
      });
i-codena
  • 11
  • 2
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()
}
Omar
  • 300
  • 5
  • 14
0

You can try configuring the header like this:

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

ANORAK_MATFLY
  • 345
  • 3
  • 7
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);
        }
    });

amboji alur
  • 175
  • 2
  • 7
-1

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")
afshar003
  • 765
  • 6
  • 6
-1

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

-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

Ernesto
  • 3,944
  • 1
  • 14
  • 29