Арт*_*нко 8 authentication routes reactjs next.js
我有一个关于 Next.js 和 React 的项目,它不使用任何库进行路由。我应该如何为未经身份验证的用户实施路由保护(受保护的路由)?或者,如果 cookie 中没有令牌,我应该重定向它们吗?
lip*_*ipp 10
您可以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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
看看这个示例代码https://github.com/lipp/login-with/blob/master/example/nextjs/with-profile.js#L8(我是作者)。
归档时间: |
|
查看次数: |
14795 次 |
最近记录: |