首页 > 解决方案 > 用于认证的 PrivateRoute 组件

问题描述

我正在开发一个 Reactjs-nodejs 应用程序。我想做一个 JWT 认证。当我们登录时,我给用户一个唯一的令牌。然后,多亏了这个令牌,如果它有效,我允许用户浏览我的路由器。我的私人路线组件就像: PrivateRoute

我的函数 getId 是这样的:

async function getId(){ let res = await axios('_/api/users/me',{config}).catch(err => { console.log(err)});

返回 res+1; }

最后,配置组件是存储在 localStorage 中的令牌:

const config = { headers: { Authorization: ${window.localStorage.getItem("token")}} };

GetId() 如果已登录,则返回用户的 id,否则为 null。

现在的问题是我的 privateRoute 总是重定向到“/”路径。我认为这是因为 axios(promise) 给我 userId 太晚了。如果你理解得很好,如果你有解决方案,请告诉我。谢谢

标签: javascriptreactjsauthenticationjwtrouter

解决方案


您可以像这样创建私有路由。

const PrivateRoute = ({ component: Component, ...props }) => {
  return (
    <Route
      {...props}
      render={innerProps =>
        localStorage.getItem("Token") ? (
          <Component {...innerProps} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
};

那么你可以使用

<PrivateRoute path="/" component={FIlname} />

推荐阅读