【问题标题】:Infinite loop when redirecting in getInitialProps in Next.js在 Next.js 的 getInitialProps 中重定向时出现无限循环
【发布时间】:2021-10-13 03:21:47
【问题描述】:

我刚刚学习了 Next.js,我在 _app.jsx 中遇到了 getInitialProps 的一个问题。 我不知道为什么会出现无限循环错误。 请告诉我为什么无限循环以及如何解决它。

const MyApp = ({ Component, pageProps }) => {

  return (
    <>
       <Component {...pageProps} />
    </>
  );
};

MyApp.getInitialProps = async ({ ctx }) => {
  console.log("run 1");
  if (ctx.res) {
    console.log("run here");
    ctx.res.writeHead(302, {
      Location: "/login",
    });
    ctx.res.end();
  }
  return {};
};

export default MyApp;

【问题讨论】:

  • 发生无限循环是因为当您在 /login 页面上时该代码也会运行。
  • 谢谢,但如果我不使用 ctx.res?.writeHead(302, { Location: "/login"});在 getInitialProps 中只记录 1 次,你知道为什么吗?

标签: node.js next.js infinite-loop


【解决方案1】:

发生无限循环是因为当您在/login 页面上时也会发生重定向。为防止出现这种情况,请确保您在该页面上时不会发生重定向。

MyApp.getInitialProps = async ({ ctx }) => {
    if (ctx.res && ctx.asPath !== "/login") {
        ctx.res.writeHead(302, {
            Location: "/login",
        });
        ctx.res.end();
     }
     return {};
};

【讨论】:

  • 相当确定这是正确的答案,另外我想知道是否需要302,你可以简单地做一个redirect(ctx, /login);
猜你喜欢
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
  • 2014-03-18
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
相关资源
最近更新 更多