29

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
    }
  })
}
1
  • I think it's because axios.default line might not executed after component mount.
    – Zeel Shah
    Jun 24, 2019 at 10:14

2 Answers 2

54

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.

0
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.