无法读取 Next.js 13 middeware 中的 req.body

Sta*_*eyy 2 javascript next.js zod next.js13

在下面的代码中,我想使用 zod 的模式验证请求正文,目前,它将失败并捕获。这是因为req.body返回的是 aReadableStream<Uint8Array>而不是它期望解析的对象。

export default async function middleware(req: NextRequest, res: NextResponse) {
  const { pathname } = req.nextUrl;
  if (pathname.startsWith('/api/user/create')) {
    try {
      createUserSchema.parse({
        body: req.body,
        params: req.nextUrl.searchParams,
      });
      return NextResponse.next();
    } catch (error: any) {
      console.log(req.body);
      return NextResponse.json(
        { success: false, message: error },
        { status: 422, headers: { 'content-type': 'application/json' } }
      );
    }
  }

  return NextResponse.next();
}
Run Code Online (Sandbox Code Playgroud)

下面是输出console.log(req.body);

<ref *1> ReadableStream {
  _state: 'readable',
  _reader: undefined,
  _storedError: undefined,
  _disturbed: false,
  _readableStreamController: ReadableStreamDefaultController {
  _controlledReadableStream: [Circular *1],
  _queue: S {
  _cursor: 0,
  _size: 0,
  _front: { _elements: [], _next: undefined },
  _back: { _elements: [], _next: undefined }
},
  _queueTotalSize: 0,
  _started: false,
  _closeRequested: false,
  _pullAgain: false,
  _pulling: false,
  _strategySizeAlgorithm: [Function],
  _strategyHWM: 1,
  _pullAlgorithm: [Function],
  _cancelAlgorithm: [Function]
}
}
Run Code Online (Sandbox Code Playgroud)

我做了一些研究,发现我需要在此 ReadableStream 上运行某种转换方法。问题是其中大多数都包含 Buffer 模块,该模块无法在 Edge 上运行,因此无法在middleware.ts. 是否有我可以使用的 Polyfill?

"next": "^13.0.7" Node v16.17.0

小智 7

您可以使用

const body = await req.json()
Run Code Online (Sandbox Code Playgroud)


eme*_*nto 5

Next.js 中间件的工作方式与 Express 中间件不同,因为它仅在导航上运行,并且不充当 API 端点的包罗万象的角色。

根据文档,您只能使用此功能访问 cookie、访问/修改请求标头以及执行重定向和重写。