首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在使用全局Axios拦截器时防止多个401错误警告

如何在使用全局Axios拦截器时防止多个401错误警告
EN

Stack Overflow用户
提问于 2020-04-17 11:03:29
回答 1查看 390关注 0票数 0

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

代码语言:javascript
运行
复制
//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);
    }
  }
);

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-18 03:42:27

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

我正在使用Router加载主页:

代码语言:javascript
运行
复制
<Router basename={"/home"}>
    <Switch>
    <AuthenticateRoute
       path="/"
       exact={true}
       component={<Main component - change this>}
/></Router>

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

代码语言:javascript
运行
复制
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?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61263461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档