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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x