重新启动计算机后,我用于拦截器的代码停止工作(我相信这就是我的项目停止工作的原因)
import axios from "axios";
let refresh = false;
axios.interceptors.response.use(
(resp) => resp,
async (error) => {
if (error.response.status === 401 && !refresh) {
refresh = true;
console.log(localStorage.getItem('refresh_token'));
const response = await axios.post(
'http://localhost:8000/token/refresh/',
{
refresh: localStorage.getItem('refresh_token'),
},
{
headers: 'Content-Type: application/json',
},
{ withCredentials: true }
);
if (response.status === 200) {
axios.defaults.headers.common['Authorization'] = `Bearer ${response.data['access']}`;
localStorage.setItem('access_token', response.data.access);
localStorage.setItem('refresh_token', response.data.refresh);
return axios(error.config);
}
}
refresh = false;
return error;
}
);
我尝试做到这一点,因此如果错误未定义,它会重新尝试执行代码
import axios from "axios";
let refresh = false;
axios.interceptors.response.use(
(resp) => resp,
async (error) => {
if (error.response && error.response.status === 401 && !refresh) {
refresh = true;
try {
const response = await axios.post(
'http://localhost:8000/token/refresh/',
{ refresh: localStorage.getItem('refresh_token') },
{ headers: { 'Content-Type': 'application/json' }, withCredentials: true }
);
if (response.status === 200) {
axios.defaults.headers.common['Authorization'] = `Bearer ${response.data['access']}`;
localStorage.setItem('access_token', response.data.access);
localStorage.setItem('refresh_token', response.data.refresh);
refresh = false;
return axios(error.config);
}
} catch (refreshError) {
console.error('Error refreshing token:', refreshError);
}
}
refresh = false;
return Promise.reject(error);
}
);
如果有效请告诉我!