vue.js - 使用 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()”中的调用也是如此。
解决方案
Can't comment sorry.
Make sure you're creating your interceptors before you're creating the Vue instance in main.js.
推荐阅读
- html - 错误地将焦点移动到字段时,如何允许屏幕阅读器宣布 ASP.NET MVC 5 表单验证消息?
- javascript - 如果条件不满足,则不会呈现任何内容的模板文字
- random - 如何在立方体中创建均匀随机分布的球体?
- scala - Spark - 加入后聚合列从 DataFrame 中消失
- javascript - 关闭以 vue-cli 3 (webpack 4.15.1) 开始的项目的热重载
- java - 为什么如果我使用循环作为输入,算法会更慢
- acumatica - 使用 Acumatica 以编程方式重新计算税款
- c# - 如何在 Telerik 报告中创建一个包含动态列数的表的子报告
- python - 如何使用 Python 将字符串列表转换为浮点数列表?
- java - 根据未知数量的键对对象列表进行排序