【问题标题】:Howto redirect from axios interceptor in reactjs app?如何在反应 js 应用程序中从 axios 拦截器重定向?
【发布时间】:2017-04-08 10:46:40
【问题描述】:

我正在尝试检查每个 axios 请求是否存在非公共路径的标头中的令牌。如果找不到令牌,我想将用户带到登录页面。 但这是在 reactjs 应用程序中。实现这一点的方法是什么?

axios.interceptors.request.use(function (config) {
 //If the header does not contain the token and the url not public, redirect to login  
 var accessToken = null;
 if(sessionStorage.getItem('currentUserString')){
  accessToken =  'bearer '+JSON.parse(sessionStorage.getItem('currentUserString')).tokenDetails.accessToken;
 }

 var configURL = config.url;
 //if token is found add it to the header
 if (accessToken) {
   if (config.method !== 'OPTIONS') {
          config.headers.authorization = accessToken;
   }
 }
 //otherwise if the request is not for login page/auth service/home redirect to login page
 else if(!isNotOpenPath(config.url)){

   //we may want to store current path in the cookies. This can be retrieved after login is successful
   //WHAT TO DO HERE TO TAKE USER TO LOGIN PAGE IN THE REACT JS APP????
  }    
}

如何向反应应用发出信号,特别是我们这里没有调度。 我可以用吗 document.location.href='\login'?

【问题讨论】:

  • 为什么不 window.location = 'loginPath' ?
  • 好的。但这就是方法。正确的?不存在特定于 reactjs 的方式吗?

标签: reactjs react-router-redux axios


【解决方案1】:

我认为在你的应用程序中使用路由的方法是使用 React Router... 然后导航你可以试试这个......

https://github.com/ReactTraining/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

【讨论】:

  • browserHistory 很有意义,也很好用 :) 谢谢!
猜你喜欢
  • 2021-08-06
  • 2017-08-29
  • 2021-07-04
  • 2021-08-11
  • 2021-11-07
  • 2022-01-09
  • 2018-09-27
  • 2021-12-25
相关资源
最近更新 更多