简体   繁体   English

Axios 刷新令牌问题

[英]Axios refresh token issue

I'm using React.useEffect() to retrieve the users list.我正在使用 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]);

On this example, fetchingUsersAction is used to set "loading" to true, and fetchUsersErrorAction to false.在此示例中,fetchingUsersAction 用于将“loading”设置为 true,将 fetchUsersErrorAction 设置为 false。 This works fine, except when the request fails due to token expiration.这工作正常,除非请求因令牌过期而失败。

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);
  }
);

This is sending a request to generate a new token and the previous request, but since the first request failed, the useEffect is going to the error section, making the "loading" false and showing the users list based on the previous state.这是发送生成新令牌和前一个请求的请求,但由于第一个请求失败,useEffect 将转到错误部分,使“加载”为 false 并根据前一个状态显示用户列表。 What is the best way to deal with this problem?处理这个问题的最佳方法是什么?

Thanks谢谢

You should create an Async fucntion inside useEffect hook and use await to wait for the response, then call the function.您应该在 useEffect 钩子中创建一个 Async fucntion 并使用 await 等待响应,然后调用该函数。 Here is one example:这是一个例子:

  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();
  }, []);

Your interceptor looks good to me.你的拦截器在我看来不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM