Next.js API 路由神秘修改 JSON 负载

Next.js API Route mysteriously modifying JSON payload

出于某种原因,当我通过 Postman 将 JSON 格式的数据作为原始文本发送时,我没有遇到任何问题。当我通过 Postman 发送与原始 JSON 完全相同的数据时(区别应该只是 content-type header 是 application/json 而不是 application/text),我最终我的双引号被删除,我的字符串切换为单引号。

原始有效载荷示例(邮递员[=3​​1=]发送这个):

{ "id": "blahblahbloo", "time": "hammer" }

意外转换(NextJS 收到这个):

{ id: 'blahblahbloo', time: 'hammer' }

明确地说,当我通过 Postman 作为 原始文本 发送时,我得到了完全相同的东西(这是我所期望的):

// Postman sends this and NextJs receives this when set to raw text    
{ "id": "blahblahbloo", "time": "hammer" }

我没有明确地做任何事情来读取 content-type 和转换数据。我遇到这个问题的端点是 NextJS 动态路由:https://nextjs.org/docs/api-routes/dynamic-api-routes

Next.js API 路由有一个 built-in 中间件,它将根据 Content-Type header 解析传入请求的 body。

来自 API Middlewares 文档(重点是我的):

API routes provide built in middlewares which parse the incoming request (req). Those middlewares are:

  • req.cookies - An object containing the cookies sent by the request. Defaults to {}
  • req.query - An object containing the query string. Defaults to {}
  • req.body - An object containing the body parsed by content-type, or null if no body was sent

将有效负载作为 application/json 发送将使 API 路由将 req.body 转换为 JavaScript object,从而剥离 double-quotes.