node.js - 快递:当接受编码为“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 }));
有谁知道我如何解析/查看身体?
解决方案
设法解决了我自己的问题。解决方案是不在正文解析器的 .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']}));
推荐阅读
- java - 如何让 RecyclerView 的其他项等待正在处理的动画
- css - 在多个按钮上切换颜色
- visual-studio-code - 在 Visual Studio 代码上自定义现有主题
- python - Python 多处理,在 for 循环中分离进程
- angular - 检查 Observable 是否未定义
- javascript - 如何为这个用 javascript 制作的日历添加工具提示
- c# - AutoMapperMappingException 奇怪的行为
- javascript - 使用我的脚本从 XML 获取属性
- rust - 带有 where 子句的不可用特征
- sql - 如果我使用的是 postGIS,如果我已经存储了几何列,是否应该存储纬度和长列?