如何在 ES6 生成器中使用 axios 拦截器?
How to use axios interceptors in ES6 generators?
目前,我有这个 Axios 调用,我想实现的是在 ES6 生成器中使用拦截器。
如果后端服务发回“401”响应,我想使用 axios 拦截器重试请求,有什么建议吗?
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)
}
就我个人而言,我更喜欢为 get/post/delete/put/patch 等使用单独的方法,但无论如何都不是必须的。
目前,我有这个 Axios 调用,我想实现的是在 ES6 生成器中使用拦截器。
如果后端服务发回“401”响应,我想使用 axios 拦截器重试请求,有什么建议吗?
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)
}
就我个人而言,我更喜欢为 get/post/delete/put/patch 等使用单独的方法,但无论如何都不是必须的。