【问题标题】:How does one set global headers in axios?如何在 axios 中设置全局标头?
【发布时间】:2017-05-01 00:49:48
【问题描述】:

嗨,我在请求拦截器中设置了默认的 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
    }
  })
}

【问题讨论】:

  • 我认为这是因为 axios.default 行在组件挂载后可能不会执行。

标签: http http-headers axios


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2021-08-27
      • 2018-11-25
      • 2019-04-11
      • 2020-06-16
      • 2022-10-18
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多