Node.js 仅当用户具有管理员角色(React、Express、NodeJS、MongoDB)时才访问页面

Node.js 仅当用户具有管理员角色(React、Express、NodeJS、MongoDB)时才访问页面,node.js,reactjs,express,Node.js,Reactjs,Express,我想允许访问一个页面,“用户”,其中显示所有在网站上注册的用户,只有当用户是管理员 这是页面的组件: <Route path="/users" exact component={Users} /> 我试过这样的方法,但没用: Router.js <AdminRoute path="/users" exact component={Users} /> AdminRoute/index.js import React, { useEffect, useStat

我想允许访问一个页面,“用户”,其中显示所有在网站上注册的用户,只有当用户是管理员

这是页面的组件:

<Route path="/users" exact component={Users} />

我试过这样的方法,但没用:

Router.js

<AdminRoute path="/users" exact component={Users} />



AdminRoute/index.js

import React, { useEffect, useState } from "react";
import { Route, Redirect } from "react-router-dom";
import axios from "axios";
import M from "materialize-css";
import { connect } from "react-redux";

function AdminRoute({ component: Component, auth, ...rest }) {
  const [user, setUser] = useState(false);

  async function loadUser() {
    try {
      const dataUser = await axios.get(
        `http://localhost:5000/api/users/my-account/${auth.user.id}`
      );
      setUser(dataUser.data);
      console.log("user ", user); <-- returns well an object with isAdmin = 
      true
      M.AutoInit();
    } catch (error) {
      console.log(error);
    }
  }

  useEffect(() => {
    if (auth.isAuthenticated) {
      loadUser();
    }
  }, []);

  return (
    <Route
      {...rest}
      render={props =>
        auth.isAuthenticated && user.isAdmin ? (
          <Component {...props} />
        ) : (
          <Redirect to="/" />
        )
      }
    />
  );
}

const mapStateToProps = state => ({
  auth: state.auth
});
export default connect(mapStateToProps)(AdminRoute);

Router.js
AdminRoute/index.js
从“React”导入React,{useffect,useState};
从“react router dom”导入{Route,Redirect};
从“axios”导入axios;
从“物化css”导入M;
从“react redux”导入{connect};
函数AdminRoute({component:component,auth,…rest}){
const[user,setUser]=useState(false);
异步函数loadUser(){
试一试{
const dataUser=wait axios.get(
`http://localhost:5000/api/users/my-帐户/${auth.user.id}`
);
setUser(dataUser.data);
console.log(“用户”,user){
如果(身份验证已验证){
loadUser();
}
}, []);
返回(
auth.isAuthenticated&&user.isAdmin(
) : (
)
}
/>
);
}
常量mapStateToProps=状态=>({
auth:state.auth
});
导出默认连接(MapStateTops)(AdminRoute);

主要问题是,如果使用管理员帐户时,由于用户仍然为false,我会被重定向,因此我需要找到一种方法,只有在loaduser功能完成后才能呈现组件?

这是某种嵌套路由吗?我确信您可以将其设置为在路由页面上工作,但我始终在页面itse中完成这项工作如果用真实的语言和陈述

{isAdmin && <div />}

auth.isAdmin中有什么内容?我感觉问题出在状态上,auth prop没有通过?或者auth没有要求的属性isAdmin?你能提供state的代码片段吗?@PrakashKarena我现在正在使用一个管理员帐户,我看到isAdmin=true,但我被重定向了,或者我应该转到pag你得到你的iAdmin了吗?@PrakashKarena我刚刚编辑了这个问题,user.isAdmin=rue和isAuthenticated=true,但我仍然得到重定向编辑看起来我的用户钩子仍然为false,当组件呈现时,我需要找到一种方法,仅在我的loadUser()之后返回是否完成我所展示的示例应该会导致组件在isAdmin更新后呈现。仅供参考,如果您将逻辑移动到相关页面/容器,则我的上述答案有效。我无法使用props.history.push,因为我在函数AdminRoute({…})中分解了结构化的props,您知道如何使用历史记录吗?我的解决方案是在您试图导航到的组件内执行此逻辑。
// This example has 3 pages: a public page, a protected
// page, and a login screen. In order to see the protected
// page, you must first login. Pretty standard stuff.
//
// First, visit the public page. Then, visit the protected
// page. You're not yet logged in, so you are redirected
// to the login page. After you login, you are redirected
// back to the protected page.
//
// Notice the URL change each time. If you click the back
// button at this point, would you expect to go back to the
// login page? No! You're already logged in. Try it out,
// and you'll see you go back to the page you visited
// just *before* logging in, the public page.

export default function AuthExample() {
  return (
    <Router>
      <div>
        <AuthButton />

        <ul>
          <li>
            <Link to="/public">Public Page</Link>
          </li>
          <li>
            <Link to="/protected">Protected Page</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/public">
            <PublicPage />
          </Route>
          <Route path="/login">
            <LoginPage />
          </Route>
          <PrivateRoute path="/protected">
            <ProtectedPage />
          </PrivateRoute>
        </Switch>
      </div>
    </Router>
  );
}

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    fakeAuth.isAuthenticated = true;
    setTimeout(cb, 100); // fake async
  },
  signout(cb) {
    fakeAuth.isAuthenticated = false;
    setTimeout(cb, 100);
  }
};

function AuthButton() {
  let history = useHistory();

  return fakeAuth.isAuthenticated ? (
    <p>
      Welcome!{" "}
      <button
        onClick={() => {
          fakeAuth.signout(() => history.push("/"));
        }}
      >
        Sign out
      </button>
    </p>
  ) : (
    <p>You are not logged in.</p>
  );
}

// A wrapper for <Route> that redirects to the login
// screen if you're not yet authenticated.
function PrivateRoute({ children, ...rest }) {
  return (
    <Route
      {...rest}
      render={({ location }) =>
        fakeAuth.isAuthenticated ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />
  );
}

function PublicPage() {
  return <h3>Public</h3>;
}

function ProtectedPage() {
  return <h3>Protected</h3>;
}

function LoginPage() {
  let history = useHistory();
  let location = useLocation();

  let { from } = location.state || { from: { pathname: "/" } };
  let login = () => {
    fakeAuth.authenticate(() => {
      history.replace(from);
    });
  };

  return (
    <div>
      <p>You must log in to view the page at {from.pathname}</p>
      <button onClick={login}>Log in</button>
    </div>
  );
}