首页 > 解决方案 > 登录前检查用户有效性

问题描述

用户登录应用程序时出现意外行为。我将 jwt 令牌存储在 cookie 中。在登录应用程序之前,我检查了 jwt 令牌是否存在以及该令牌在后端是否有效。

下面是我的代码。这是 app.js。

class App extends Component {
 render() {
    return (
      <BrowserRouter>
        <Layout>
          <LoginRoute></LoginRoute>
        </Layout>
      </BrowserRouter>
    );
  }
}

LoginRoute 组件如下。

const LoginRoute = withRouter(({ history }) => (
  isValidUser() ? (
    <Switch>
      <Route path="/incident-reporting" component={Home}></Route>
      <Redirect path='/' to='/incident-reporting/home' />
      <NotFound />
    </Switch>
  ) : (
      <Switch>
        <Route path="/" exact component={Login}></Route>
        <NotFound></NotFound>
      </Switch>
  )
))

这是 isValidUser()

const isValidUser = () => {
  if (cookies.get("token")) {
    let token = cookies.get("token")
    axios.get("https://0.0.0.0:9094/auth/v1.0.0/user-info", {
      headers: { 'Authorization': 'Bearer ' + token }
    }).then(
      response => {
        return true;
      }
    ).catch(
      error => {
        return false;
      }
    )
    //return true
  } else {
    return false;
  }
}

但我无法使用有效令牌登录应用程序。在执行 axios 发布请求之前isValidUser()返回。undefined如何解决这个问题呢?

标签: javascriptreactjs

解决方案


您需要等待 isValidUser 完成。为此,您可以这样做:

const LoginRoute = withRouter(async ({ history }) => (
  let isUserValid = await isValidUser()
  isUserValid ? (
    <Switch>
      <Route path="/incident-reporting" component={Home}></Route>
      <Redirect path='/' to='/incident-reporting/home' />
      <NotFound />
    </Switch>
  ) : (
      <Switch>
        <Route path="/" exact component={Login}></Route>
        <NotFound></NotFound>
      </Switch>
  )
))

在 isValidUser 上:

const isValidUser = () => {
  if (cookies.get("token")) {
    let token = cookies.get("token")
    return axios.get("https://0.0.0.0:9094/auth/v1.0.0/user-info", {
      headers: { 'Authorization': 'Bearer ' + token }
    }).then(
      response => {
        return true;
      }
    ).catch(
      error => {
        return false;
      }
    )
    //return true
  } else {
    return false;
  }
}

推荐阅读