【问题标题】:Express: req.body empty when accept-encoding is 'gzip, deflate'快递:当接受编码为“gzip,放气”时,req.body 为空
【发布时间】:2019-05-27 12:48:31
【问题描述】:

我正在尝试接收来自第 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 的正文解析器来解析响应。根据 Express docs 的说法,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.js express gzip body-parser


    【解决方案1】:

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

    以下两个代码 sn-ps 中的任何一个都可以工作:

    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']}));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-19
      • 2018-02-27
      • 2021-04-14
      • 2016-12-18
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多