Javascript 如何在ES6生成器中使用axios拦截器?
目前,我有这个Axios调用,我想要实现的是在ES6生成器中使用拦截器 如果后端服务返回“401”响应,我想使用axios拦截器重试请求,有什么建议吗Javascript 如何在ES6生成器中使用axios拦截器?,javascript,reactjs,ecmascript-6,axios,redux-saga,Javascript,Reactjs,Ecmascript 6,Axios,Redux Saga,目前,我有这个Axios调用,我想要实现的是在ES6生成器中使用拦截器 如果后端服务返回“401”响应,我想使用axios拦截器重试请求,有什么建议吗 const token = '...'; export function* getUsers(user) { return yield axios({ headers: { Accept: "Aplication/json", Authorization: `Bearer ${token}
const token = '...';
export function* getUsers(user) {
return yield axios({
headers: {
Accept: "Aplication/json",
Authorization: `Bearer ${token}`,
},
method: "get",
url: '/getUsers/:id'
})
.then(data => data)
.catch(e => e)
}
也许你可以试试这样的东西
import axios from "axios";
export const getClient = (token) => {
const options = {};
if (token !== null) {
options.headers = { Authorization: `Bearer ${token}` };
}
const instance = axios.create(options);
instance.interceptors.response.use((response) => response, (error) => {
if (error.response.status === 401) {
window.location = '/logout'; // Or whatever you want to do
}
return Promise.reject(error);
});
return instance;
};
export function* getUsers(user) {
return yield getClient('JTW_TOKEN').get('/getUsers/:id').then(data => data).catch(e => e)
}
就我个人而言,我更喜欢使用单独的方法来获取/发布/删除/放置/修补等,但无论如何它都不是必须的。使用的是
yeild
你必须吗?是@nicholasnet,因为我使用的是redux saga