Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly set axios default headers

I'm using reactjs for my project but I have one issue, in config.js file where i set my global axios configurations, I'm setting default headers for axios requests but when i make axios request it does not send those headers in requests.

config.js

import axios from 'axios';

const instance = axios.create({
    baseURL: 'URL/api'
});

export const setAuthToken = (token) => {
    if (token) {
        // Apply to every request
        instance.defaults.headers.common['Authorization'] = 'Bearer ' + token;
    } else {
        // Delete auth header
        delete instance.defaults.headers.common['Authorization'];
    }
};

export default instance;

Login.js

import axios from '../../../config';
import { setAuthToken } from '../../../config';
axios
            .post('/auth/signin', {
                username: email,
                password: password
            })
            .then((res) => {
                setCurrentUser(res.data);
                setAuthToken(res.data.accessToken);
                setLoading(false);
            })
            .catch((err) => {
                console.log(err);
                setLoading(false);
                setError(true);
            });
like image 764
Zayn Avatar asked Jan 13 '20 07:01

Zayn


People also ask

How do I set the default header in Axios?

Instead of adding the headers to each request, you can put them as default headers, and they will apply to all the requests. To do so, use the defaults. headers property of the axios object. This snippet will add the x-rapidapi-key header to all the requests.

How do you put headers on Axios interceptors?

use method to update each request header and set the access token in the Authorization HTTP header. We target the Authorization header from the config. headers object and set a Bearer token, which is stored in localStorage , as its value. We can also call the axios.

What is Axios defaults baseURL?

Global axios defaults axios. defaults. baseURL = 'https://api.example.com'; axios.

What is Axios default content type?

Axios converts this Javascript data to JSON by default. It also sets the “content-type” header to “application/json”. However, if you pass a serialized JSON object as data, Axios treats the content type as “application/x-www-form-urlencoded” (form-encoded request body).


2 Answers

You can use axios interceptors for this task.

1-) Inside the successfull login, put the retrieved token to the localStorage. Remove setAuthToken line.

 .then((res) => {
                setCurrentUser(res.data);
                localStorage.setItem("token", res.data.accessToken);
                setLoading(false);
            })

2-) Add this interceptor to your axios instance.

const instance = axios.create({
    baseURL: 'URL/api'
});

instance.interceptors.request.use(
  function(config) {
    const token = localStorage.getItem("token"); 
    if (token) {
      config.headers["Authorization"] = 'Bearer ' + token;
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);
like image 63
SuleymanSah Avatar answered Sep 20 '22 14:09

SuleymanSah


I had to create the header object structure within the instance for global header overriding to work:

The code snippet below does not working (but it does not raise any error); global header is used when using the instance:

// Index.js
axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';

// myAxios.js
const instance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com'
});

instance.defaults.headers.common['Authorization'] = 'AUTH_TOKEN_FROM_INSTANCE';

This does work, instance header overrides the global default:

// Index.js
axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';

// myAxios.js
const instance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  headers: {
    common: {
      Authorization: 'AUTH_TOKEN_FROM_INSTANCE'
    }
  }
});

It seems to me that this object structure should be created by default when using #create.

===========================================================================

Additionally, if you want to unset the header don't use delete. Here's a test:

it('should remove default headers when config indicates', function (done) {
  var instance = axios.create();
  instance.defaults.headers.common['Content-Type'] = 'application/json';

  instance.post('/foo/bar/', {
    firstName: 'foo',
    lastName: 'bar'
  }, {
    headers: {
      'Content-Type': null
    }
  });

  getAjaxRequest().then(function (request) {
    testHeaderValue(request.requestHeaders, 'Content-Type', null);
    done();
  });
});
like image 34
haMzox Avatar answered Sep 16 '22 14:09

haMzox