【发布时间】:2021-10-07 07:19:12
【问题描述】:
我正在使用next-connect 将一些快速中间件应用于我的 next.js 应用程序。在尝试添加csrf中间件时,遇到如下错误:
res.redirect is not a function
此错误仅在我在 getServerSideProps 中应用中间件时出现,它在我的 API 端点中运行良好。
例如:
// in /pages/api/test.ts
nc()
.use(db)
.use(initializedSession)
.use(csrfProtection)
.use(initializedPassport)
.use(initializedPassportSession)
.post(
passport.authenticate("local", {failureRedirect: "/login"}),
(req: NextApiRequest, res: NextApiResponse, next) => {
return res.redirect("/");
}
)
确实有效,但在 getServerSideProps 中应用相同的反应页面:
// In /pages/login.tsx
export const getServerSideProps: GetServerSideProps = async ({req, res}) => {
await nc()
.use(db)
.use(initializedSession)
.use(csrfProtection)
.use(initializedPassport)
.use(initializedPassportSession)
.run(req, res);
return {
props: {
csrfToken: req.csrfToken(),
},
};
};
不起作用并导致res 没有重定向方法。
我不太确定这种行为,但我确定我错过了一些愚蠢的东西。有什么想法吗?
【问题讨论】:
-
啊哈,这完全有道理!有什么理由会出现这种情况吗?有没有办法在
getServerSideProps中扩展http.ServerResponse? -
@brc-dd 谢谢,我也在看!我会尝试用它来转换响应。看起来很简单,但我感觉会有一些陷阱,否则 next.js 团队可能会自己实现它。无论哪种方式,您的回答都是我正在寻找的答案!我不能让它正确,因为它太短了。如果您想要其中一些 Stackoverflow 点,请随时写一些更长的内容,我会将您的回复标记为解决方案:)
标签: next.js