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

时间:2016-12-15 15:18:30

标签: javascript json node.js express post

我有一个node.js + Express应用程序。它有一个我提供给第三方服务的webhook。该服务向我的webhook发送一个POST请求,其中包含JSON正文,如下所示:

  

{" split_info" :" null"," customerName" :"商家名称",   " additionalCharges" :" null"," paymentMode":" CC",   "散列":" a31ff1b91fd9b8ae9c82f38b02348d21fsdfd86cc828ac9a0acf82050996372cc656de3db0fe3bf9af52b73a182a77787241f3e19ec893391607301b03e70db8&#34 ;,   "状态" :"发放付款"," paymentId" :" 551731" ,   " productInfo":" productInfo"," customerEmail":" test@gmail.com",   " customerPhone":" 9876543212"," merchantTransactionId":" jnn",   "金额":" 100.0"," udf2":" null"," notificationId" :" 4"," udf1":" null",   " udf5":" null"," udf4":" null"," udf3":" null& #34;" ERROR_MESSAGE":"否   错误"}

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

以下是我的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           

很确定我错过了什么或做错了什么,但我无法弄明白。

感谢。

1 个答案:

答案 0 :(得分:0)

我终于找到了发生的事情。

正文解析器的工作方式是它只会尝试解析他们理解Content-Type的请求。这主要是因为你可以堆叠它们(app.use多个解析器类型没有冲突),也因为你通常不想解析一个失败的请求(Content-Type:text / html不太可能通过一个例如,JSON.parse)。

我最终收到了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)); }); ,这甚至都不是有效的Content-Type标头值期间。身体解析器模块拒绝接受它,因为这是胡言乱语。此模块允许您设置一个函数,该函数允许您放置要执行过滤的任何自定义逻辑。

我必须将身体解析器放在我的路由器代码中,仅用于此webhook案例。

{{1}}

@svens感谢您的帮助。