出于某种原因,当我通过 Postman 将 JSON 格式的数据作为原始文本发送时,我没有遇到任何问题。当我通过 Postman 发送与原始 JSON 完全相同的数据时(区别应该只是 content-type
header 是 application/json
而不是 application/text
),我最终去掉了双引号并将字符串切换为单引号。
原始负载示例( postman 发送此):
{ "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 路由有一个内置的 bodyParser
中间件,它将根据 Content-Type
header 解析传入请求的主体。
来自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 bycontent-type
, ornull
if no body was sent
将负载作为 application/json
发送将使 API 路由将 req.body
转换为 JavaScript 对象,从而去除双引号。
虽然默认情况下会自动启用 bodyParser
中间件,但如果您想自己使用主体,您可以禁用它。
// In the API route
export const config = {
api: {
bodyParser: false
}
}
关于json - Next.js API Route 神秘修改 JSON payload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70887907/