【问题标题】:axios interceptor not called in mounted() with Vue.js使用 Vue.js 未在 mount() 中调用 axios 拦截器
【发布时间】:2021-01-18 20:55:23
【问题描述】:

我在我的 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()”中的调用也是如此。

【问题讨论】:

  • 看起来很奇怪。你确定sessionStorage.getItem('token') 会返回一些东西吗? (也许可以试试console.log 确定...)
  • 试过console.log,完全没有调用拦截器。

标签: vue.js axios


【解决方案1】:

抱歉,无法评论。

确保在 main.js 中创建 Vue 实例之前创建拦截器。

【讨论】:

  • 我相信这是关键点,谢谢 - 我在创建 Vue 实例后创建了我的拦截器。将那段代码向上移动,现在一切似乎都在正常工作。
猜你喜欢
  • 2018-11-01
  • 2021-05-10
  • 2022-11-03
  • 2022-01-25
  • 2020-09-20
  • 2019-12-19
  • 2019-06-26
  • 2012-08-18
  • 2019-03-15
相关资源
最近更新 更多