Next.js:getServerSideProps中的res.redirect(res.redirect不是函数)

Bra*_*sen 3 next.js

我正在next-connect将一些快速中间件应用到我的 next.js 应用程序中。在尝试添加csrf中间件时,遇到以下错误:

res.redirect is not a function
Run Code Online (Sandbox Code Playgroud)

仅当我在 中应用中间件时才会出现此错误getServerSideProps,它在我的 API 端点中工作正常。
这适用于例如:

res.redirect is not a function
Run Code Online (Sandbox Code Playgroud)

getServerSideProps确实有效,但在反应页面中应用相同的方法:

// 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("/");
    }
 )
Run Code Online (Sandbox Code Playgroud)

不起作用并导致res没有重定向方法。

我不太确定这种行为,但我确信我错过了一些愚蠢的事情。有人有想法吗?

brc*_*-dd 5

res的对象属于getServerSideProps类型http.ServerResponse,并且没有名为 的方法redirect。而在 API 中,res对象NextApiResponse一些额外的帮助器,例如redirect方法。这就是您的代码在 API 逻辑中运行良好的原因。

但 Next.js 建议这样做:

注意:您不应该fetch()getServerSideProps. 相反,直接导入 API 路由中使用的逻辑。您可能需要针对此方法稍微重构代码。

从外部 API 获取就可以了!

因此,您的方法的核心非常好,但要使其发挥作用,您需要“稍微重构”您的代码。现在,Next.js 在内部使用了一个apiResolver中间件。您可以尝试使用它或您的自定义解析器。

请注意,内部 API 很容易发生更改,因此通常不建议在生产代码中直接使用它们。但是您可以轻松地将逻辑从链接文件克隆到您自己的共享库。

要处理响应部分,您可以执行以下操作:

import type { GetServerSideProps, NextApiRequest, NextApiResponse } from 'next';

import {
  redirect,
  sendData,
  sendJson,
  sendStatusCode,
} from 'next/dist/next-server/server/api-utils'; // or from 'custom-api-resolver'

// component logic here ...

const getServerSideProps: GetServerSideProps = async ({
  req: apiReq,
  res: apiRes,
}) => {
  const req = apiReq as NextApiRequest;
  const res = apiRes as NextApiResponse;

  res.status = (statusCode) => sendStatusCode(res, statusCode);
  res.send = (data) => sendData(req, res, data);
  res.json = (data) => sendJson(res, data);
  res.redirect = (statusOrUrl: number | string, url?: string) =>
    redirect(res, statusOrUrl, url);

  // api logic here...

  return { props: {} };
};

export { getServerSideProps };
Run Code Online (Sandbox Code Playgroud)

参考:

我还没有对此进行彻底的测试,但对于基础知识来说,这应该可以正常工作。