javascript - 用于认证的 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 太晚了。如果你理解得很好,如果你有解决方案,请告诉我。谢谢
解决方案
您可以像这样创建私有路由。
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} />
推荐阅读
- sass - 尝试创建空 SCSS 列表时出现语法错误
- python - 矩阵上的 Linspace
- kotlin - 如何将 rxjava2 Zip 函数(来自 Single/Observable)的 arity 推广到 n 个 Nullable 参数而不丢失其类型?
- google-apps-script - 如果单元格上的日期超过 30 天,如何从 Sheet1 剪切线并粘贴到 Sheet2?
- python - 如何解决此错误“create_text_channel 错误”
- http - 试图获取联赛统计数据以计算内部比赛的胜率
- python - 如何获取 Python 列表中相邻重复元素的索引?
- tensorflow - 在 Google AI Platform 上服务的 TensorFlow 模型在线预测实例批次太慢
- firebase - 集成 Firebase 身份验证和身份平台
- mysql - MYSQL 获取不同阶段的最高列值的 COUNT