【问题标题】:Nextjs redirect in _app.js 'The page isn’t redirecting properly'Nextjs 在 _app.js 中重定向“页面未正确重定向”
【发布时间】: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。

标签: node.js redirect next.js


【解决方案1】:

您收到该错误是因为您最终触发了无限重定向循环到 /login 页面。

使用无效令牌登陆任何页面都会重定向到/login 页面。当此重定向发生时,它将触发另一个 App.getInitialProps 调用,这将导致另一个重定向到 /login 页面,因为令牌仍然无效,依此类推。

当当前页面是/login 页面时,您可以通过添加检查来防止这种行为。这可以通过多种方式处理,但我将在这里留下一个示例。

if (!token) {
    const isProtectedRoute = ctx.pathname === '/account'
    if (isProtectedRoute) {
        redirectUser(ctx, '/login')
    }
} else if (ctx.pathname !== "/login") { // To avoid redirect loop
    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET)
    } catch(err) {
        console.error(err)
        redirectUser(ctx, '/login')
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-28
    • 2017-01-18
    • 2011-08-11
    • 2018-06-08
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多