reactjs - Next.js + react 中的路由守卫
问题描述
我有一个关于 Next.js 和 React 的项目,它不使用任何库进行路由。我应该如何为未经身份验证的用户实施路由保护(受保护的路由)?或者如果 cookie 中没有令牌,我应该重定向它们吗?
解决方案
您可以getInitialProps
通过一些适当的方式办理登机手续。评估 cookie 以决定是否重定向的逻辑。
import Router from 'next/router'
const redirectToLogin = res => {
if (res) {
res.writeHead(302, {Location: '/login'})
res.end()
res.finished = true
} else {
Router.push('/login')
}
}
class ProtectedPage extends React.Component {
static async getInitialProps ({req, res}) {
// get cookie from req.headers or from document.cookie in browser
// this cookie must not contain sensitive information!
const profile = getProfileFromCookie(req)
if (!profile) {
redirectToLogin(res)
}
}
}
看看这个示例代码https://github.com/lipp/login-with/blob/master/example/nextjs/with-profile.js#L8(我是作者)。
推荐阅读
- angular - 在 Google Chrome 浏览器中使用 Angular 7 和 ASP.Net Core 2.2 的 ERR_INVALID_HTTP_RESPONSE
- angular - 在 Angular 中,是否可以根据用户是否经过身份验证来加载不同的模块?
- node.js - 使用 nodejs 编码的 jwt 令牌进行解码 使用颤振(飞镖)制作
- swift - Swift / ARKit:将对象节点放置在检测到的表面上而不触摸屏幕
- apache - Java 重定向 + 域
- tags - 带有 CoNLL 2003 NER 任务描述的可能标签列表是什么?
- javascript - 在 UWP 中使用 Composition 制作移动圆圈
- botframework - 在 MS Bot 框架中的第二个 Slack 工作空间上与 Slack Channel 通信的问题
- sql-server - 如何加入 To Select 语句
- python - 请求标头中的 HMAC apisign 但标头必须是 str 错误?