标签:javascript authentication reactjs nextjs
我有这段代码来检查用户是否经过身份验证
const withAuth = AuthComponent => {
class Authenticated extends Component {
static async getInitialProps (ctx) {
let componentProps
if (AuthComponent.getInitialProps) {
componentProps = await AuthComponent.getInitialProps(ctx)
}
return {
...componentProps
}
}
componentDidMount () {
this.props.dispatch(loggedIn())
}
renderProtectedPages (componentProps) {
const { pathname } = this.props.url
if (!this.props.isAuthenticated) {
if (PROTECTED_URLS.indexOf(pathname) !== -1) {
// this.props.url.replaceTo('/login')
Router.replace('/login') // error
}
}
return <AuthComponent {...componentProps} />
}
render () {
const { checkingAuthState, ...componentProps } = this.props
return (
<div>
{checkingAuthState ? (
<div>
<h2>Loading...</h2>
</div>
) : (
this.renderProtectedPages(componentProps)
)}
</div>
)
}
}
return connect(state => {
const { checkingAuthState, isAuthenticated } = state.data.auth
return {
checkingAuthState,
isAuthenticated
}
})(Authenticated)
}
它工作得很好但我在尝试重定向用户时收到此错误:
No router instance found. You should only use “next/router” inside the client side of your app.
如果我尝试使用this.props.url.replaceTo(‘/ login’)我会收到此警告
Warning: ‘url.replaceTo()’ is deprecated. Use “next/router” APIs.
所以这让我发疯,我想知道是否有办法实现这种重定向,或者在这种情况下控制身份验证的另一种方法只是一个线索将是伟大的.
解决方法:
您应该检查您的代码是在服务器端执行还是在客户端执行.
这条路:
const isClient = typeof document !== 'undefined'
isClient && Router.replace('/login')
要处理服务器端的重定向,您只需使用服务器即可.
例如:
server.get("/super-secure-page", (req, res) => {
// Use your own logic here to know if the user is loggedIn or not
const token = req.cookies["x-access-token"]
!token && res.redirect("/login")
token && handle(req, res)
})
仅仅为了您的信息,我受到了next.js code example的启发
标签:javascript,authentication,reactjs,nextjs 来源: https://codeday.me/bug/20190705/1391038.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。