首页 > 解决方案 > 使用全局axios拦截器时如何防止出现多次401错误警告

问题描述

在 ReactJS 项目中,我设置了一个全局 Axios 拦截器来处理 401 错误并重定向到登录页面。如果服务器返回 401 错误,这将按预期工作。

//global interceptor for handling 401 (invalid token) response.
axios.interceptors.response.use(
  function (response) {
    console.log("Axios defaut interceptor");
    return response;
  },
  function (error) {
    if (401 === error.response.status) {
      alert(
        "Your session has expired. You will be redirected to the login page."
      );
      window.location = "/login";
    } else {
      return Promise.reject(error);
    }
  }
);

问题是从主页类组件的constructor() 方法发送了多个GET 请求。这会导致多次显示警报消息。

处理错误并仅重定向到登录页面一次的最佳方法是什么?

标签: reactjsaxios

解决方案


解决方案是在加载页面之前验证令牌是否存在。

我正在使用路由器加载主页:

<Router basename={"/home"}>
    <Switch>
    <AuthenticateRoute
       path="/"
       exact={true}
       component={<Main component - change this>}
/></Router>

在 AuthenticateRoute 组件中,验证是否存在具有有效到期日期的令牌。

class AuthenticatedRoute extends Component {
    render() {
       var isValidToken = false;
       const token = localStorage.getItem(USER_TOKEN);
       if (token === null) isValidToken = false;
       var decodedToken = jwt.decode(token, { complete: true });
       if (decodedToken.payload === null) isValidToken = false;
       //Get the current time in seconds.
       var dateNow = new Date();
       var nowDateSeconds = parseInt(dateNow.getTime() / 1000);
       //Check if token expiry time greater than current time (valid token)
       if (decodedToken.payload.exp > nowDateSeconds) {
            isValidToken = true;
       }
       if (isValidToken ) {
            return <Route {...this.props} />
        } else {
            return <Redirect to="/login" /> 
        }

    }
}

如果令牌无效,则不会加载主页。注意:此代码不会授权/验证令牌。它只是在加载主要组件之前检查是否存在有效的日期令牌。

有关浏览器中 JWT 令牌验证的更多详细信息 - React - 如何在发送发布请求之前检查 JWT 是否有效?


推荐阅读