本文介绍了当多个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 Component上调用4个API,并且发生此错误,则同一代码将运行4次,这意味着4次我将发送刷新令牌并获得auth令牌,而我显然只希望运行一次
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调用时,仅运行一次响应拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!