繁体   English   中英

Node.js无法读取我的Webhook中的POST JSON数据

[英]Node.js unable to read POST JSON data in my webhook

我有一个node.js + Express应用程序。 它已经提供给第三方服务了。 该服务使用JSON主体向我的Webhook发送POST请求,如下所示:

{“ split_info”:“ null”,“ customerName”:“商家名称”,“ additionalCharges”:“ null”,“ paymentMode”:“ CC”,“ hash”:“ a31ff1b91fd9b8ae9c82f38b02348d21fsdfd86cc828ac9a0acf82050b3e9a9e9a9e3a3e3b3e3e3b0b3e3b0e3e3b0e3e3b3e0b0e3b0e3b0e0b0e8e3b0e3b0e3b0e8e3e8e3b0e3b0e3b0e3b0b0e8e3b0bf0b使用者,“ paymentId”:“ 551731”,“ productInfo”:“ productInfo”,“ customerEmail”:“ test@gmail.com”,“ customerPhone”:“ 9876543212”,“ merchantTransactionId”:“ jnn”,“ amount”:“ 100.0”,“ udf2”:“ null”,“ notificationId”:“ 4”,“ udf1”:“ null”,“ udf5”:“ null”,“ udf4”:“ null”,“ udf3”:“ null” ,“ error_Message”:“没有错误”}

我正在使用body-parser模块读取POST数据。 但是,当我执行req.body时,它给出了[object Object],如果我执行了JSON.stringify(req.body),则它给出了{}即空。 如果我尝试访问响应中的键,例如req.body.paymentMode,那么它将给出未定义的信息。

这是我的Webhook路由器代码: mywebhook.js

var express = require('express');
var router = express.Router();

router.post('/success', function(req, res){

    //this is where I need to strip the JSON request
    //req.body or JSON.stringify(req.body) or anything that works
    //if everything is okay then I send
    res.sendStatus(200);

});

module.exports = router;

我的app.js看起来像这样:

var express = require('express');                               
var exphbs = require('express-handlebars');
var router = express.Router();                                  
var bodyParser = require('body-parser');

var mywebhook = require('./routes/mywebhook');  

var app = express(); 

.
.
.
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json


app.use('/callwebhook', mywebhook);

.
.
.
so on           

可以肯定的是,我遗漏了一些东西或做错了什么,但是我无法弄清楚。

谢谢。

我终于发现发生了什么事。

主体解析器的工作方式是,它将仅尝试解析他们理解Content-Type的请求。 这主要是因为您可以堆叠它们(应用程序使用多种解析器类型而不会发生冲突),并且还因为您通常不希望解析将失败的请求(内容类型:text / html不太可能通过例如JSON.parse)。

我最终被发送*/*; charset=UTF-8 */*; charset=UTF-8 ,它甚至不是有效的Content-Type标头值周期。 主体分析器模块拒绝接受它,因为那是乱码。 该模块确实允许您设置一个函数,该函数允许您放置要执行过滤的任何自定义逻辑。

我只需要针对这种webhook情况将主体解析器放入路由器代码中。

var bodyParser = require('body-parser');
var customParser = bodyParser.json({type: function(req) {
    return req.headers['content-type'] === '*/*; charset=UTF-8';
}});

router.post('/success', customParser, function(req, res){
    console.log(JSON.stringify(req.body));
});

@svens谢谢您的帮助。

暂无
暂无

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

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