my axios interceptor is:-
axios.interceptors.response.use((response, error) => {
const originalRequest = response.config;
if (response.data.status === 'Token is Expired' && originalRequest.url === '/api/refresh') {
this.props.history.push('/logout');
Promise.reject(error);
}
if (response.data.status === 'Token is Expired' && !originalRequest._retry) {
originalRequest._retry = true;
const playerToken = localStorage.getItem('accessToken');
return axios
.get('/api/refresh', {
headers: {
Authorization: `bearer ${playerToken}`,
},
})
.then(res => {
console.log('from refreshtoken', res);
const stringRes = JSON.stringify(res);
const parsedRes = JSON.parse(stringRes);
const stringData = JSON.stringify(parsedRes.data);
const parsedData = JSON.parse(stringData);
const stringToken = JSON.stringify(parsedData.data);
const parsedToken = JSON.parse(stringToken);
if (parsedData.success == true) {
localStorage.setItem('accessToken', playerToken);
axios.response.config.headers['Authorization'] = `bearer ${parsedToken}`;
return Promise.resolve();
return axios(originalRequest);
} else {
this.props.history.push('/logout');
}
})
.catch(err => {
console.log('from refreshtoken', err);
});
}
return Promise.reject(error);
});
My code is running but when my refresh token API is called first time, It also returns the same status "Token is expired" due to which i am logged out of the app. This is happening only in interceptor. When i am calling Refresh API outside of interceptor, it returns with a refresh token.
Does my code have mistakes? or it is some other coding fault entirely.
Please answer & tell me the right way to do it & where do i place my interceptor??
Currently it is placed in a Component which is called just after login.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…