Doi*_*ois 2 json mime-types double-quotes postman next.js
由于某种原因,当我通过 Postman 作为原始文本发送 JSON 格式的数据时,没有任何问题。当我通过 Postman 作为原始 JSON 发送完全相同的数据时(区别应该只是标题content-type而application/json不是application/text),我最终会删除双引号,并将字符串切换为单引号。
原始有效负载示例(邮递员发送此):
{ "id": "blahblahbloo", "time": "hammer" }
Run Code Online (Sandbox Code Playgroud)
意外的转换(NextJS收到此信息):
{ id: 'blahblahbloo', time: 'hammer' }
Run Code Online (Sandbox Code Playgroud)
需要明确的是,当我通过 Postman作为原始文本发送时,我得到了完全相同的结果(这正是我所期望的) :
// Postman sends this and NextJs receives this when set to raw text
{ "id": "blahblahbloo", "time": "hammer" }
Run Code Online (Sandbox Code Playgroud)
我没有明确执行任何操作来读取content-type和转换数据。我遇到此问题的端点是 NextJS 动态路由:https ://nextjs.org/docs/api-routes/dynamic-api-routes
Next.js API 路由有一个内置bodyParser中间件,它将根据请求Content-Type头解析传入请求的正文。
来自API 中间件文档(重点是我的):
API 路由提供内置中间件来解析传入请求 (
req)。这些中间件是:
req.cookies- 包含请求发送的 cookie 的对象。默认为{}req.query- 包含查询字符串的对象。默认为{}req.body- 包含由 解析的正文的对象content-type,或者null如果没有发送正文
发送有效负载 asapplication/json将使 API 路由转换req.body为 JavaScript 对象,从而去掉双引号。
虽然bodyParser默认情况下会自动启用中间件,但如果您想自己使用主体,可以将其禁用。
// In the API route
export const config = {
api: {
bodyParser: false
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2407 次 |
| 最近记录: |