我将apisauce用于我的React应用程序的HTTP工作,我也使用React-router和Redux Saga。
我有一个问题,我们有没有办法在apisauce中创建一个拦截器,有没有可能将我们的应用程序重定向到/login路由?
我添加了监视器,这是apisauce的一个功能,但我不知道如何将我的应用程序重定向到/login路由。
感谢您的帮助。
我的显示器示例:
constructor() {
this.api = apisauce.create({
baseURL: env.API_URL,
headers: {
Authorization: `Bearer ${localStorage.getItem('user') || ''}`,
},
timeout: 15000,
});
this.api.addMonitor(this.tokenMonitor);
}
private tokenMonitor(response: any) {
const { ok, status } = response;
if (!ok && status !== 200) {
// I should do redirect here
localStorage.removeItem('user');
}
}发布于 2020-04-26 12:06:17
也许你可以使用,就像这样:
constructor() {
this.api = apisauce.create({
baseURL: env.API_URL,
headers: {
Authorization: `Bearer ${localStorage.getItem('user') || ''}`,
},
timeout: 15000,
});
api.axiosInstance.interceptors.request.use(
(config) => {
const token = JSON.parse(localStorage?.getItem('token')) || {};
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// config.headers['Content-Type'] = 'application/json';
return config;
},
(error) => {
Promise.reject(error);
},
);
this.api.addMonitor(this.tokenMonitor);
}
private tokenMonitor(response: any) {
const { ok, status } = response;
if (!ok && status !== 200) {
// I should do redirect here
localStorage.removeItem('user');
}
}我希望这能对你有所帮助。
https://stackoverflow.com/questions/56058670
复制相似问题