我想做的是,当用户的AcccessToken在时间到期后无效时,我想用存储在LocalStorage中的RefreshToken刷新当前用户的AccessToken。但我陷入了无限循环。
这是我的代码。
axios.interceptors.request
axios.interceptors.request.use(
config => {
config.headers['Content-Type'] = 'application/json';
return config;
},
error => {
Promise.reject(error)
}
);
axios.interceptors.response
axios.interceptors.response.use((response) => {
return response
},
function (error) {
const originalRequest = error.config;
console.log("originalRequest = " + originalRequest);
if (error.response.status === 403) {
console.log("Interceptors.response => " + error.response);
const refreshToken = localStorage.getItem('refreshToken');
return axios.post('http://localhost:8080/jpa/system/getat', { "refreshToken": refreshToken })
.then(res => {
if (res.status === 200) {
sessionStorage.setItem('accessToken', res.data.accessToken);
axios.defaults.headers.common['Authorization'] =
sessionStorage.getItem('accessToken');
return axios(originalRequest);
}
})
}
return Promise.reject(error);
});
我用'_retry'修复了此错误
axios.interceptors.response.use
axios.interceptors.response.use((response) => {
return response
},
function (error) {
const originalRequest = error.config;
console.log("InterCeptors.Response got an error");
if (error.response.status === 403 && !originalRequest._retry) {
console.log("InterCeptors.Response.originalRequest => \n " + JSON.stringify(originalRequest));
console.log("InterCeptors.Response got an error in status403 & !retry");
originalRequest._retry = true;
return axios.post('http://localhost:8080/jpa/system/getat', { "refreshToken": localStorage.getItem('refreshToken') })
.then(res => {
if (res.status === 200) {
console.log("InterCeptors.Response got succeed");
sessionStorage.setItem('accessToken', res.data.data.accessToken);
axios.defaults.headers.common['Authorization'] = sessionStorage.getItem('accessToken');
return axios(originalRequest);
}
})
}
return Promise.reject(error);
});