如何在axios中设置全局标头?

时间:2016-12-15 12:07:11

标签: http http-headers axios

您好我在请求拦截器中设置默认axios标头但是这些标头在另一个函数中无法访问...在axios axios documentation中提到global-axios-defaults是全局的...下面是我的示例代码需要帮助

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

在页面加载上,componentDidmount执行但在此函数中未定义axios默认标头

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

2 个答案:

答案 0 :(得分:17)

您可以为每个XHR调用设置默认的自定义标题,如下所示:

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

您还可以像这样添加配置:

  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';

此外,您可以创建传递给实例的配置。

答案 1 :(得分:1)

<块引用>

在您的 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);
  }
);