node.js - 在 Next.js 的 getInitialProps 中重定向时出现无限循环
问题描述
我刚刚学习了 Next.js,但我对getInitialProps
in有一个问题_app.jsx
。我不知道为什么会出现无限循环错误。请告诉我为什么无限循环以及如何解决它。
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
页面上时也会发生重定向。为防止出现这种情况,请确保您在该页面上时不会发生重定向。
MyApp.getInitialProps = async ({ ctx }) => {
if (ctx.res && ctx.asPath !== "/login") {
ctx.res.writeHead(302, {
Location: "/login",
});
ctx.res.end();
}
return {};
};
推荐阅读
- django - 我可以切换使用 django 吗?
- php - 调用 GET Rest API 时出现 403 错误
- python - Python:使用函数引用 DataFrame 中的列
- eclipse - 在 Eclipse 内部 JavaBuilder 中启用 DEBUG 标志
- logback - logback 为同一个 appender 同时打开多个文件
- c - 为什么我不能在 C 中创建这些二维数组的副本?
- google-apps-script - 从下拉列表中选择“删除” clearContent(); 细胞
- python - Selenium 使用 python 返回不正确的列数
- jquery - 如何找到总折扣 - jQuery
- css - 如何在带有 HTML 输出的 tufte 风格的 Bookdown 中重置每章的旁注编号?