gpt4 book ai didi

javascript - Vue.js - 导出 axios 拦截器

转载 作者:行者123 更新时间:2023-12-04 08:08:48 26 4
gpt4 key购买 nike

大家晚上好,这里我的 VueJS 拦截器有问题。我不明白我的问题从何而来,我正在拔头发......
我看过几个教程,看过几个关于stackoverflow的主题,但我根本不明白发生了什么。
当我打开调试器时,它会被触发,但是当我切换到“axios.interceptors”时,它告诉我 axios 未定义,这是不可理解的......

import axios from 'axios';

debugger;
axios.interceptors.response.use(function (response) {
console.log(response);
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
console.log(error);
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});

const token = localStorage.getItem('token');

export default axios.create({
baseURL: process.env.VUE_APP_URL_API,
headers: {
Authorization: `Bearer ${token}`
}
})
上面的代码是在我的 VueX Store 中调用的。
import Http from "../../api/http";

export default {
state: {
customers: {},
customer: {},
},
getters: {
customers: state => state.customers,
},
mutations: {
SET_CUSTOMERS(state, customers) {
state.customers = customers;
}
},
actions: {
loadCustomers({commit}) {
Http.get('/customers').then(result => {
commit('SET_CUSTOMERS', result.data.data );
}).catch(error => {
throw new Error(`API ${error}`);
});
}
}
};
我想触发 http 代码 401 来注销我的用户并销毁浏览器中的 token 。
如果有人可以帮助我,我会很高兴,非常感谢。
问候,
克里斯托夫

最佳答案

如拦截器docs ,就在示例拦截器的下方,如果您使用实例,则必须向其中添加拦截器:

import axios from 'axios';

const token = localStorage.getItem('token');

const instance = axios.create({
baseURL: process.env.VUE_APP_URL_API,
headers: {
Authorization: `Bearer ${token}`
}
})

instance.interceptors.response.use(function (response) {
console.log(response);
// Any status code within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
console.log(error);
// Any status codes outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});

export default instance;

关于javascript - Vue.js - 导出 axios 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66082103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com