Mailgun的webhook POST身体似乎是空的
我正试图处理来自Mailgun反弹webhook的http post消息。 当发送给Mailgun的Postbin服务时,当然会发现所有的数据。 但我现在发送POST到我的本地服务器的发展目的,我得到的是空的JSON数组。 我使用testingWebhook。
意图是尽可能简单,除了我们的主要服务。 对于我开始使用nodejs / expressjs来创build独立的web服务来作为中继接收来自Mailgun邮件反弹的POST消息并通知pipe理员关于退回的电子邮件地址。
现在我不明白为什么我不能得到相同的数据,在Postbin中可见。
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mailgun = require('mailgun-js')({apiKey: 'key-...', domain: 'mymailgundomain.com'}); app.use(bodyParser.urlencoded({ extended: true })); function router(app) { app.post('/webhooks/*', function (req, res, next) { var body = req.body; if (!mailgun.validateWebhook(body.timestamp, body.token, body.signature)) { console.error('Request came, but not from Mailgun'); res.send({ error: { message: 'Invalid signature. Are you even Mailgun?' } }); return; } next(); }); app.post('/webhooks/mailgun/', function (req, res) { // actually handle request here console.log("got post message"); res.send("ok 200"); }); } app.listen(5000, function(){ router(app); console.log("listening post in port 5000"); });
我从Mailgun的testingWebhook使用像http://mylocalhostwithpublicip.com:5000/webhooks/mailgun
代码结构从https://github.com/1lobby/mailgun-js复制。 也许我在这里错过了一些基本的东西,因为我自己弄不清楚。
您没有看到req.body
填充的原因是因为body-parser
模块不支持multipart/form-data
请求。 对于这些types的请求,你需要一个不同的模块,如multer
, multer
/ connect-busboy
, multiparty
或formidable
。
如果您的内容types(由logging console.dir(req.headers['content-type'])
)显示为'application/x-www-form-urlencoded'
,并且您正在使用body-parser
,请尝试添加以下行:
bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false }))
为了使它与multer一起工作,你可以使用.any()(version 1.1.0)
对我来说,它的工作是这样的(假设包括Muller,并声明为“multer”)
post('/track', multer.any(),function(req, res){ //if body is a string, parse the json var data=(typeof req.body=='string')?JSON.parse(req.body):req.body; //if data is an object but you can't verify if a field exists with hasOwnProperty, force conversion with JSON if(typeof data=='object' && typeof data.hasOwnProperty=='undefined') data=JSON.parse(JSON.stringify(data)); //data is your object });
var multer = require('multer'); var msg = multer(); post('/track', msg.any(), function(req, res){ console.log(req.body); }
当Content-type ='multipart / alternative'时,我创build一个自定义parsing器来获取req.body中的数据。