reactjs - axios拦截器的更好实现方式
问题描述
我已经解决了我之前的问题并且整个代码可以正常工作,但是如果有更好的方法来编写这个大函数,我很感兴趣,使用 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,
},
});
};
解决方案
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 直接使用此服务
推荐阅读
- java - 当您有小段时,如何显示每条可能采取的路径?
- r - 循环读取 CSV,添加列,用文件名填充列,堆栈 data.frames?
- async-await - 量角器无法理解的失败 - 功能超时确保承诺在 5000 毫秒内解决
- mysql - 如何简化以下 SQL 查询?
- java - 从 JSON 数组中删除对象
- python - 什么是好的做法 - 我应该创建一个新对象还是重用同一个对象?
- python - 如何从相对路径中为 pip3 模块添加前缀
- dart - 有没有一种方法可以在同一路线上以不同的方式在不同的时间显示两个小部件,一次由一个按钮控制?
- haskell - 修改可扩展记录时重叠实例
- java - 如何根据Java中的特定元素对多维对象数组进行排序