Axios刷新令牌问题

时间:2020-09-29 13:04:45

标签: reactjs react-redux axios react-typescript

我正在使用React.useEffect()来检索用户列表。

React.useEffect(() => {
dispatch(UsersActions.creators.fetchingUsersAction());
UsersApi.methods.getUsers().then(
  (res) => {
    dispatch(UsersActions.creators.fetchUsersSuccessAction(res.data));
  },
  (e) => {
    dispatch(UsersActions.creators.fetchUsersErrorAction());
  }
);
}, [dispatch]);

在此示例中,将fetchingUsersAction设置为“ loading”为true,将fetchUsersErrorAction设置为false。效果很好,除非请求由于令牌过期而失败。

ApiClient.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      const refresh = JSON.stringify({
        refreshToken: localStorage.getItem("refresh"),
      });
      AuthenticationApi.methods.refresh(refresh).then((res) => {
        if (res.data.accessToken) {
          localStorage.setItem("token", res.data.accessToken);
        }
        ApiClient.defaults.headers.common["Authorization"] =
          "Bearer " + res.data.accessToken;
        originalRequest.headers["Authorization"] =
          "Bearer " + res.data.accessToken;
        return ApiClient(originalRequest);
      });
    }
    return Promise.reject(error);
  }
);

这正在发送一个生成新令牌和上一个请求的请求,但是由于第一个请求失败,所以useEffect转到错误部分,将“ loading”设置为false,并根据先前的状态显示用户列表。解决此问题的最佳方法是什么?

谢谢

1 个答案:

答案 0 :(得分:0)

您应该在 useEffect hook 中创建一个 Async fucntion 并使用 await 等待响应,然后调用该函数。下面是一个例子:

  useEffect(() => {
    const getRoles = async () => {
      await authService.roles().then((res) => {
        //Do your stuff.
        console.log(res);
      }).catch((error) => {
        console.log(`'Catching the error: '${error}`);
      });
    };
    //Call the recent created function.
    getRoles();
  }, []);

我觉得你的拦截器不错。