【问题标题】:body-parser ignores type parameterbody-parser 忽略类型参数
【发布时间】:2021-03-07 12:39:42
【问题描述】:

我有 Content-Type: application/vnd.surveymonkey.response.v1+json 的入站请求。我正在尝试在他们身上使用body-parserbody-parserjson 工厂方法的 documentation 声明:

返回仅解析 json 并且仅查看 Content-Type 标头与 type 选项匹配的请求的中间件。

[...]

type 选项用于确定中间件将解析的媒体类型。此选项可以是字符串、字符串数组或函数。如果不是函数,则 type 选项直接传递给 type-is 库,它可以是扩展名(如 json)、mime 类型(如 application/json)或带有通配符的 mime 类型(如 / 或 */json)。如果是函数,则类型选项称为 fn(req),如果请求返回真值,则解析请求。默认为 application/json。

我尝试了各种参数,但无论我放什么,解析器中间件继续接受application/json,同时拒绝application/vnd.surveymonkey.response.v1+json。事实上,当我在 type 函数中添加 console.debug 语句时,它永远不会打印,所以看起来 type 参数被完全忽略了。

我做错了吗? body-parser 需要做什么才能尊重 type 参数?

import * as bodyParser from 'body-parser';
import * as express from 'express';

const app = express();
app.use(
  bodyParser.json({
    // type: 'application/vnd.surveymonkey.response.v1+json', // doesn't work
    // type: ['application/vnd.surveymonkey.response.v1+json'], // doesn't work
    // type: ['application/*'], // doesn't work
    // type: (req) => /application\/(.+\+)?json/.test(req.headers['Content-Type'] as string), // doesn't work
    type: (req) => console.debug('Hello world!'),
  })
);

app.post(`/`, (req, res) => {
  console.log('Request: ', req.body);
  res.status(200).send();
});

【问题讨论】:

    标签: node.js express mime-types content-type body-parser


    【解决方案1】:

    It turns out 问题是我在 Firebase Functions 上运行,它已经在入站请求上运行 body-parser。添加body-parser 的另一个实例是无操作的,这就是它被忽略的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多