【问题标题】:How to prevent multiple 401 error warnings when using global Axios interceptor使用全局axios拦截器时如何防止出现多次401错误警告
【发布时间】:2020-07-30 11:20:59
【问题描述】:

在 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请求。这会导致多次显示警报消息。

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

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

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

    我使用路由器加载主页:

    <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 - How to check if JWT is valid before sending a post request?

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2018-04-25
      • 2021-10-30
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2019-10-22
      相关资源
      最近更新 更多