首页 > 解决方案 > 快递:当接受编码为“gzip,放气”时,req.body 为空

问题描述

我正在尝试从第 3 方接收 webhook。虽然我可以看到 content-length > 0,但 console.logging req.body 只会产生 {}。请求被发送到路由“/v2/wtevr/report/wtevr”。

这些是从 webhook POST 请求收到的标头:

accept: '*/*',
'accept-encoding': 'gzip, deflate',
'user-agent': 'rest-client/2.0.2 (linux-gnu x86_64) ruby/2.5.3p105',
'content-type': 'application/vnd.wtevr.wtevr.leadwebhook+json;version=0.0.2',
'content-length': '254',
host: 'api.mysite.co.uk'

我正在使用 Express 的 body-parser 来解析响应。根据 Express文档,body-parser 支持“gzip”和“deflate”编码的自动膨胀。我已经指定了内容类型来捕获请求并将其解压缩,但它不起作用。这就是我的代码的样子:

app.use(
  function(req, res, next) {
    if (req.url === '/v2/wtevr/report/wtevr') {
      next();
    }
  }
)
app.use(bodyParser.json({type: ['application/json', 'application/vnd.wtevr.wtevr.leadwebhook+json;version=0.0.2']}));
app.use(bodyParser.urlencoded({ extended: true }));

有谁知道我如何解析/查看身体?

标签: node.jsexpressgzipbody-parser

解决方案


设法解决了我自己的问题。解决方案是不在正文解析器的 .json 函数的 'type' 选项中将自定义内容类型指定为精确字符串,而是使用通配符或将其精确指定为函数。

以下两个代码片段中的任何一个都可以工作:

app.use(bodyParser.json({type: (req) => req.get('Content-Type') === 'application/vnd.wtevr.wtevr.leadwebhook+json;version=0.0.2'}));
app.use(bodyParser.json());

或者

app.use(bodyParser.json({type: ['application/json', 'application/*+json']}));

推荐阅读