I have an interceptor like this
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)
})
}
})
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
Interceptor is an API gateway server built for accepting API requests from the client applications and routing them to the appropriate backend services. May it be a single service or multiple services to be called in a single API call, interceptor provides you with the necessary tools to control your API request flow.
Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received. Interceptors are methods which are triggered before or after the main method.
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);
});
}
});
I hope this helps you ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With