由于某种原因,当我通过 Postman 作为原始文本发送 JSON 格式的数据时,没有任何问题。当我通过 Postman 发送与原始 JSON 完全相同的数据时(区别应该只是content-type
标头是application/json
代替application/text
),我最终删除了双引号,并将字符串切换为单引号。
原始有效负载示例(Postmansends this):
{ "id": "blahblahbloo", "time": "hammer" }
意外的转换(NextJSreceives this):
{ id: 'blahblahbloo', time: 'hammer' }
需要明确的是,当我发送时,我得到了完全相同的东西(这正是我所期望的)raw text通过邮递员:
// 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 https://nextjs.org/docs/api-routes/dynamic-api-routes
Next.js API 路由有一个内置的bodyParser
中间件将根据传入请求的正文解析Content-Type
header.
来自API中间件 https://nextjs.org/docs/api-routes/api-middlewares文档(重点是我的):
API 路由提供内置中间件来解析传入的
要求 (req
)。这些中间件是:
-
req.cookies
- 包含请求发送的 cookie 的对象。默认为{}
-
req.query
- 包含查询字符串的对象。默认为{}
req.body
- 包含解析主体的对象content-type
, or null
如果没有尸体被送来
将有效负载发送为application/json
将使 API 路由转换为req.body
到 JavaScript 对象,因此去掉双引号。
虽然bodyParser
中间件默认自动启用,如果您想自己使用 body,可以禁用它。
// In the API route
export const config = {
api: {
bodyParser: false
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)