Sending the bearer token with axios Sending the bearer token with axios reactjs reactjs

Sending the bearer token with axios


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.


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.


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