json - Next.js API Route 神秘修改 JSON payload

标签 json next.js postman mime-types double-quotes

出于某种原因,当我通过 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 by content-type, or null 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/

相关文章:

javascript - Nextjs - 在服务器端访问 url 参数

c# - 错误请求 400 从 API 补丁方法返回

python - 将 pandas 列转换为 JSON 字符串

java - 是否可以通过 json-schema 检查是否仅存在必填字段?

javascript - 如何在 NextJS 中处理重定向到外部 url?

node.js - 使用 node/postgres 在 Postman 上使用图像测试创建/更新 API

c# asp.net core Bearer错误="invalid_token"

javascript - AngularJS 无法在 Chrome(Mac 和 Windows)中运行,但可以在 Safari 中运行

javascript - 以列表格式动态显示 JSON 值

reactjs - 如何开发可重用的类似 Bootstrap 的组件