我正在尝试将 axios 拦截器与刷新令牌一起使用,但是当我的令牌已过期时。我在interceptors.response 中的错误代码没有执行。我能做些什么来解决这个问题,我也收到了 200 的状态代码,这对我来说没有多大意义。
这里也是我的代码
proctedInstance.interceptors.request.use(
async config => {
const accesstoken = localStorage.getItem('accesstoken');
config.headers = {
'Authorization': `Bearer ${accesstoken}`,
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
return config;
},
error => {
Promise.reject(error);
}
)
proctedInstance.interceptors.response.use((response) => {
console.log(response);
return response
},
function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
return axios.post('http://localhost:4000/refresh_token')
.then(res => {
if (res.status === 200) {
localStorage.setItem('accesstoken', res.data.accesstoken)
console.log('my token res.data.accesstoken', res.data.accesstoken);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('accesstoken');
return axios(originalRequest);
}
})
}
return Promise.reject(error);
})
export const onProtected = async () => {
const results = await (await proctedInstance.post('/protected')).data
if(results.data === 'This is protected data.'){
return true;
} else
return false;
}
感谢任何帮助
答案 0 :(得分:0)
试着让它像这样:
proctedInstance.interceptors.response.use(
function (response) {
return response;
},
function (error) {
const access_token = localStorage.getItem("accesstoken");
if (error.response.status === 401 && access_token) {
//Your logic to refresh token and reattempt request
} else {
console.error(error);
}
return Promise.reject(error);
}
);