【发布时间】:2017-05-01 06:11:31
【问题描述】:
我有一个 node.js + Express 应用程序。它有一个我提供给第三方服务的 webhook。该服务使用 JSON 正文向我的 webhook 发送一个 POST 请求,如下所示:
{"split_info" : "null", "customerName" : "商户名称", “additionalCharges”:“null”,“paymentMode”:“CC”, “哈希”:“a31ff1b91fd9b8ae9c82f38b02348d21fsdfd86cc828ac9a0acf82050996372cc656de3db0fe3bf9af52b73a182a77787241f3e19ec893391607301b03e70db8”, “状态”:“释放付款”,“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","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
很确定我错过了什么或做错了什么,但我无法弄清楚。
谢谢。
【问题讨论】:
-
你确定请求的
Content-type是application/vnd.api+json吗?这对我来说似乎很奇怪。 -
你说得对,当我使用 hookbin.com 测试第三方 webhook 时,它说内容类型是:/。所以我将 app.js 中的内容类型更改为 app.use(bodyParser.json({ type: '/' }));
-
好的,我把类型改成了'/' 但是req.body还是空的。
-
我再次高度怀疑这一点。只需
console.log(req.get('Content-Type'));在您的 webhook 处理程序中,您就会知道... -
好的,所以当我打印出它给出的内容类型时:asterisk/asterisk;charset=UTF-8
标签: javascript json node.js express post