gpt4 book ai didi

javascript - axios如何添加拦截器功能?

转载 作者:行者123 更新时间:2023-11-30 06:11:20 25 4
gpt4 key购买 nike

好吧,所以我想在我的全局 axios 配置中添加一个响应拦截器,如果出现 401 错误,它会重试请求一次,在刷新 token 。

这是我当前的全局 axios 配置:

import axios from "axios";

export default axios.create({
baseURL: process.env.REACT_APP_API,
headers: {
"content-type": "application/json"
},
responseType: "json"
});

现在我做了研究,我的问题已经得到解决 here ,但是,我不知道如何在我的 axios 配置文件的答案中附加或使用拦截器函数(在我根据我的需要编辑它之后)拦截器函数如下所示:

createAxiosResponseInterceptor() {
const interceptor = axios.interceptors.response.use(
response => response,
error => {
// Reject promise if usual error
if (errorResponse.status !== 401) {
return Promise.reject(error);
}

/*
* When response code is 401, try to refresh the token.
* Eject the interceptor so it doesn't loop in case
* token refresh causes the 401 response
*/
axios.interceptors.response.eject(interceptor);

return axios.post('/api/refresh_token', {
'refresh_token': this._getToken('refresh_token')
}).then(response => {
saveToken();
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
return axios(error.response.config);
}).catch(error => {
destroyToken();
this.router.push('/login');
return Promise.reject(error);
}).finally(createAxiosResponseInterceptor);
}
);
}

非常感谢!

最佳答案

如果我对问题的理解正确,您需要在自定义公理实例上调用拦截器创建函数。所以像这样:

import axios from "axios";

const instance = axios.create({
baseURL: process.env.REACT_APP_API,
headers: {
"content-type": "application/json"
},
responseType: "json"
});

function createAxiosResponseInterceptor(axiosInstance) {
const interceptor = axiosInstance.interceptors.response.use(
response => response,
error => {
// Reject promise if usual error
if (errorResponse.status !== 401) {
return Promise.reject(error);
}

/*
* When response code is 401, try to refresh the token.
* Eject the interceptor so it doesn't loop in case
* token refresh causes the 401 response
*/
axiosInstance.interceptors.response.eject(interceptor);

return axiosInstance.post('/api/refresh_token', {
'refresh_token': this._getToken('refresh_token')
}).then(response => {
saveToken();
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
return axiosInstance(error.response.config);
}).catch(error => {
destroyToken();
this.router.push('/login');
return Promise.reject(error);
}).finally(createAxiosResponseInterceptor);
}
);
}

createAxiosResponseInterceptor(instance);

export default instance;

并使createAxiosResponseInterceptor函数将axios实例作为参数。

关于javascript - axios如何添加拦截器功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748321/

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