简体   繁体   English

没有内容类型 header 的快速解析 JSON

[英]Express parse JSON without content-type header

I have an Express API which is replacing an existing API.我有一个 Express API,它正在替换现有的 API。 The existing API receives JSON data but does not require the content-type header.现有的 API 接收 JSON 数据,但不需要内容类型 header。 Express seems to require this header for any parsing of the body into JSON and is returning undefined. Express 似乎需要此 header 才能将正文解析为 JSON 并且返回未定义。

Is there a way to get Express to assume the data is a JSON type without the content-type header set?有没有办法让 Express 假设数据是 JSON 类型而没有设置内容类型 header ?

The parseing of request bodies is done using the body-parser library which has an option to change the allowed content-type header values .请求正文的解析是使用body-parser库完成的,该库具有更改允许的内容类型 header 值的选项。 Here an example that replaces the check with a function that always returns true, thereby always trying to parse the body as json.这里是一个用 function 替换检查的示例,它始终返回 true,因此始终尝试将正文解析为 json。

const bodyParser = require('body-parser');

app.use(bodyParser.json({
  type(req) {
    return true;
  }
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM