【发布时间】:2021-02-19 22:07:47
【问题描述】:
我正在构建 nextjs 应用程序的用户身份验证部分。除了受保护的路线外,我已经完成了大部分工作。我正在尝试处理 _app.js 中的身份验证部分。这是文件:
import App from 'next/app'
import '../styles/globals.css'
import { parseCookies } from 'nookies'
import { redirectUser } from '../utils/auth'
import jwt from 'jsonwebtoken'
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
const { token } = parseCookies(ctx)
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
if (!token) {
const isProtectedRoute = ctx.pathname === '/account'
if (isProtectedRoute) {
redirectUser(ctx, '/login')
}
} else {
try {
const verified = jwt.verify(token, process.env.JWT_SECRET)
} catch(err) {
console.error(err)
redirectUser(ctx, '/login')
}
}
return { pageProps }
}
render() {
const { Component, pageProps } = this.props;
return (
<Component {...pageProps} />
)
}
}
export default MyApp
还有我的 redirectUser 文件:
import cookie from 'js-cookie';
import Router from 'next/router';
export function handleLogin(token) {
cookie.set('token', token)
Router.push('/account');
}
export function redirectUser(ctx, location) {
if (ctx.req) {
ctx.res.writeHead(302, { Location: location })
ctx.res.end()
} else {
Router.push(location)
}
}
当用户没有令牌时,auth 部分会正确重定向,但如果该令牌被更改为无效,我会收到重定向错误:
The page isn’t redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
我已经确认是第二个redirectUser 调用导致了这个错误。即使我将它放在 getInitialProps 函数底部的 else 条件之外,我也会得到相同的结果。
【问题讨论】:
-
您是否在 Firefox 以外的浏览器上收到错误消息?您是否尝试过清除浏览器的缓存/cookie?
-
我在其他浏览器中也出现错误。当我试图处理提供了无效令牌的用例时,清除 cookie 会破坏目的。
-
能否请您告诉我您在此项目中使用的 next.js 版本是什么?我已将我的下一个 js 从 9.5.x 更新到 10.2.x,我收到错误消息:ctx.res.writehead is not a function。