一种更好的实现 axios 拦截器的方法
2021-07-19
897
我已经解决了我之前的问题并且整个代码运行正常,但是我感兴趣的是是否有更好的方法来编写这个大函数,使用 axios 拦截器。
export const handleFetchData =
(accessToken, refreshToken) => async (dispatch) => {
authentification.interceptors.response.use((response) => {
if (response.data.statusCode === 200) {
console.log("valid");
dispatch({ type: "USER_ME", payload: response });
} else {
console.log("invalid");
axios({
method: "post",
url: "http://142.93.134.108:1111/refresh",
headers: { Authorization: `Bearer ${refreshToken}` },
}).then((res) => {
localStorage.setItem("accessToken", res.data.body.access_token);
localStorage.setItem("refreshToken", res.data.body.refresh_token);
axios
.get("http://142.93.134.108:1111/me", {
headers: {
Authorization: "Bearer " + localStorage.getItem("accessToken"),
},
})
.then((reply) => dispatch({ type: "USER_ME", payload: reply }));
});
}
return response;
});
await authentification.get("http://142.93.134.108:1111/me", {
headers: {
Authorization: "Bearer " + accessToken,
},
});
};
1个回答
create a wrapper around the axios which act as the interceptor/middleware.
//interceptor.js
import axios from 'axios';
function http(method, endpoint, payload, headers) {
switch (method){
case 'GET':
axios.get(endpoint).then((data, status)=>{
if (status === 200) {
console.log("valid");
dispatch({ type: "USER_ME", payload: response });
}
//similarly for other methods POST,PUT, PATCH ...
}
}
export default http;
在你的组件中不要直接使用 axios,而是使用此服务
priston lewis
2021-07-19