How does one set global headers in axios?

44,842

Solution 1

You can set the default Custom Headers in Axios for every XHR call like this:

axios.defaults.headers.common = {
  "X-Requested-With": "XMLHttpRequest",
  "X-CSRFToken": "example-of-custom-header"
};

You can also add configurations onward like this:

  window.axios.defaults.headers.post['xsrfCookieName'] = 'CSRFToken';
  window.axios.defaults.headers.post['xsrfHeaderName'] = 'X-CSRFToken';
  window.axios.defaults.headers.post['responseType'] = 'json';
  window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Also, you can create a configuration passed into an instance.

Solution 2

on your MAIN.JS

import axios from "axios";
const base = axios.create({
  baseURL: "http://127.0.0.1:8000/", 
});

Vue.prototype.$http = base;

  Vue.prototype.$http.interceptors.request.use(
  config => {
      let accessToken = localStorage.getItem('token');
      if (accessToken) {
          config.headers = Object.assign({
              Authorization: `Bearer ${accessToken}`
          }, config.headers);
      }
      return config;
  },
  error => {
      return Promise.reject(error);
  }
);
Share:
44,842

Related videos on Youtube

code.king
Author by

code.king

Updated on April 10, 2021

Comments

  • code.king
    code.king about 3 years

    Hi I'm setting default axios headers in request interceptor but these headers are not accessible in another function... in axios axios documentation it is mentioned that global-axios-defaults are global...below is my sample code need help

    axios.interceptors.request.use(function (config) {
      axios.defaults.headers.accesstoken= "some_access_token"
      axios.defaults.headers.client = "some_client"
      axios.defaults.headers.uid = "some_uid"
      return config;
    },function (error) {
      return Promise.reject(error);
    });
    

    On page load componentDidmount executes but axios default headers are undefined in this function

    componentDidMount: function() {
      console.log(axios.defaults.headers) #its giving me undefined
      axios.get("http://some_url_for_get_request.json", {
        headers: {
          accesstoken: axios.defaults.headers.accesstoken,
           uid: axios.defaults.headers.uid,
           client: axios.defaults.headers.client
        }
      })
    }
    
    • Zeel Shah
      Zeel Shah about 5 years
      I think it's because axios.default line might not executed after component mount.