多个 API 调用时只运行一次响应拦截器 [英] run response interceptor only once when multiple API calls
本文介绍了多个 API 调用时只运行一次响应拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的拦截器
axios.interceptors.response.use(undefined, err=> {
const error = err.response;
console.log(error);
if (error.status===401 && error.config && !error.config.__isRetryRequest) {
return axios.post(Config.oauthUrl + '/token', 'grant_type=refresh_token&refresh_token='+refreshToken,
{ headers: {
'Authorization': 'Basic ' + btoa(Config.clientId + ':' + Config.clientSecret),
'Content-Type': 'application/x-www-form-urlencoded,charset=UTF-8'
}
})
.then(response => {
saveTokens(response.data)
error.config.__isRetryRequest = true;
return axios(error.config)
})
}
})
并且一切正常,但是如果我在一个 React 组件上有 4 个 API 调用,并且发生此错误,则相同的代码将运行 4 次,这意味着我将发送 4 次刷新令牌并获得身份验证令牌,显然我只想运行一次
And everything is working, but if I have like in my case 4 API calls on one React Component, and this error happens the same code will be run 4 times, meaning 4 times I will send my refresh token and get the auth token, and I would want to run it only once obviously
推荐答案
我认为您可以使用以下方式对身份验证请求进行排队:
I think you can queue authentication requests with something like:
let authTokenRequest;
// This function makes a call to get the auth token
// or it returns the same promise as an in-progress call to get the auth token
function getAuthToken() {
if (!authTokenRequest) {
authTokenRequest = makeActualAuthenticationRequest();
authTokenRequest.then(resetAuthTokenRequest, resetAuthTokenRequest);
}
return authTokenRequest;
}
function resetAuthTokenRequest() {
authTokenRequest = null;
}
然后在你的拦截器中...
And then in your interceptor...
axios.interceptors.response.use(undefined, err => {
const error = err.response;
if (error.status===401 && error.config && !error.config.__isRetryRequest) {
return getAuthToken().then(response => {
saveTokens(response.data);
error.config.__isRetryRequest = true;
return axios(error.config);
});
}
});
希望对你有帮助;)
这篇关于多个 API 调用时只运行一次响应拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文