node.js - React Router v6 中的 protected 路由,使用 useState,但始终返回 false

标签 node.js reactjs authentication async-await react-router

这就是我正在尝试做的事情。我从 google 获取 JWT,暂时将其存储在 sessionStorage 中,然后通过我的 API 发送以进行服务器端验证。

这是 protected 路由,我用它来环绕我的 protected 元素。就像这样

 <Route element={<PrivateRouteClient />}>  
                <Route path="/CDashboard" element={<Client_dashboard /> }>
 </Route>




import axios from 'axios';
import React, {useEffect, useState} from 'react';
import {Navigate}  from 'react-router-dom';
import {Outlet}  from 'react-router-dom';

 function PrivateRouteClient() {
  const [isAuth, setIsAuth] = useState(false);
  
  axios.post('http://localhost:8080/something/something', {credential: sessionStorage.getItem("token")})
  .then(function (res){
    console.log(Boolean(res.data["UserAuth"]));
    setIsAuth(Boolean(res.data["UserAuth"]));
    console.log("hi");
    return isAuth;
  })
  console.log(isAuth)
  return isAuth ? <Outlet /> : <Navigate to="/login/Client" />;
}

  
export default PrivateRouteClient

我无法使路由异步,因为它会返回一个 promise ,而这不是一个有效的 React 组件,它会抛出错误。 不太明白我哪里做错了!

感谢您的阅读和帮助!

最佳答案

有几个问题,(1) 您发出 POST 请求是无意的副作用,(2) 代码是异步的,而 React 组件的主体是同步的。

使用安装useEffect Hook 发出POST请求并等待请求解决。使用中间 isAuth 状态值“保持”,直到 POST 请求以任何一种方式解析(无论用户是否通过身份验证)。

function PrivateRouteClient() {
  const [isAuth, setIsAuth] = useState(); // initially undefined

  useEffect(() => {
    axios.post(
      'http://localhost:8080/something/something',
      { credential: sessionStorage.getItem("token") },
    )
      .then(function (res){
        console.log(Boolean(res.data["UserAuth"]));
        setIsAuth(Boolean(res.data["UserAuth"]));
        return isAuth;
      });
  }, []);

  console.log(isAuth);

  if (isAuth === undefined) return null; // or loading indicator, etc...

  return isAuth ? <Outlet /> : <Navigate to="/login/Client" />;
}

关于node.js - React Router v6 中的 protected 路由,使用 useState,但始终返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70658559/

相关文章:

node.js - 如何使用 htaccess 的替代方法对 nodejs 应用程序进行密码保护

node.js - 是否可以在不访问cmd.exe的情况下学习node.js?

node.js - 错误 : certificate has expired in Node

javascript - 为什么 React-app 状态没有在这里重新渲染?如何让状态及时更新

javascript - 在哪里存储ajax请求的参数

java - Twitter4j:身份验证凭据 (https://dev.twitter.com/pages/auth) 丢失或不正确

ios - React Native-是否有用于使用Apple ID登录的库?

javascript - Node.Js 异步使用

javascript - AngularJS : factory $http. get 请求不断获取 html 文件作为返回

javascript - axios如何类似jQuery ajax方法设置表单数据?