How to set request headers in axios library?

January 13, 2019 No comments QA axios JS

Axios is one of the best javascript HTTP client based on promises. It works on all modern browsers, and has many features:

  • Make XMLHttpRequests from the browser,
  • Make HTTP requests from node.js,
  • Supports the Promise API,
  • Intercept request and response,
  • Transform request and response data,
  • Cancel requests,
  • Automatic transforms for JSON data,
  • Client side support for protecting against XSRF.

Axios allows you to set custom headers to your ajax requests. It can be done in three ways:

1. In a single http request

let conf = {
  headers: {
    header1: value1,
    header2: value2,
    header3: value3
    ...
  }
}

let data = {
  'POST_PARAMETER': "POST_PARAM_VALUE"
}

axios.post(URL, data, config).then(res => {
    console.log(res);
});

2. Global configuration for all requests or separately for POST/GET/DELETE method

a) To set header1 with value = value1 for all POST request use:

axios.defaults.headers.post['header1'] = 'value1';

b) To set header1 with value = value1 for all requests use:

axios.defaults.headers.common['header1'] = 'value1';

3. Set for specific axios instance

a) Create single axio instance:

let instance = axios.create({
  headers: {
    post: { 
      header1: 'value1',
      header2: 'value2',
      header3: 'value3'
      ...
    }
  }
})

b) Set global headers for specific instance

instance.defaults.headers.post['header1'] = 'value1';
instance.defaults.headers.post['header2'] = 'value2';
instance.defaults.headers.get['header3'] = 'value3';

b) Use interceptor to set headers for requests

instance.interceptors.request.use(config => {
  config.headers.post['header1'] = 'value1';
  config.headers.get['header2'] = 'value2';
  return config;
});
{{ message }}

{{ 'Comments are closed.' | trans }}