首页 > 解决方案 > 使用 Vue.js 未在 mount() 中调用 axios 拦截器

问题描述

我在我的 Vue 应用程序中使用 JWT,并且需要使用 Axios 为每个 AJAX 请求提交必要的授权标头。在我的“main.js”文件中,我设置了一个拦截器,它执行以下操作:

axios.interceptors.request.use(req => {
  if(sessionStorage.getItem('token')) {
    req.headers['Authorization'] = auth.getAuthHeader();
  }
  return req;
});

但是,在一个组件中,我在mounted() 中发出AJAX 请求,因此:

mounted() {
  this.salePrep();
}

这是方法:

async salePrep(){
  const response = await this.$axios.get(contextPath + "/sale/prep");
  this.$store.commit("setData", response.data);
},

由于我不明白的原因,没有为此调用 axios 拦截器。mount() 阶段有什么我没有掌握的吗?为什么这个 AJAX 调用会有所不同?一旦组件被加载,所有的 AJAX 调用都成功地使用了拦截器——即设置了 Authorization 标头。只是不是mounted()中的那个。

编辑:我已经确定在“created()”中的调用也是如此。

标签: vue.jsaxios

解决方案


Can't comment sorry.

Make sure you're creating your interceptors before you're creating the Vue instance in main.js.


推荐阅读