首页 > 解决方案 > 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,
      },
    });
  };

标签: reactjsaxios

解决方案


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 直接使用此服务


推荐阅读