Mailgun webhook POST机身似乎是空的

时间:2015-01-16 13:09:38

标签: node.js webhooks mailgun

我正试图处理来自Mailgun bounce webhook的http帖子消息。当将其发送到Mailgun的Postbin服务时,当然会找到所有数据。但我现在将POST发送到我的localhost服务器进行开发,我得到的只是空的json数组。我使用Test Webhook。

除了我们的主要服务之外,意图是保持这种简单。那是因为我开始使用nodejs / expressjs创建独立的webservice作为中继来接收来自Mailgun的电子邮件退回的POST消息,并通知管理员有关退回的电子邮件地址。

现在我无法理解为什么我没有获得与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");
});

我正在使用像http://mylocalhostwithpublicip.com:5000/webhooks/mailgun

这样的网址从Mailgun的Test Webhook运行

https://github.com/1lobby/mailgun-js复制代码结构。可能我在这里缺少一些基本的东西,因为我无法弄清楚自己。

5 个答案:

答案 0 :(得分:14)

您没有看到填充req.body的原因是body-parser模块不支持multipart/form-data请求。对于这类请求,您需要一个不同的模块,例如multerbusboy / connect-busboymultipartyformidable

答案 1 :(得分:6)

如果您的内容类型(通过记录console.dir(req.headers['content-type'])显示)为'application/x-www-form-urlencoded',并且您正在使用body-parser,请尝试添加以下行:

    bodyParser = require('body-parser')
    app.use(bodyParser.urlencoded({ extended: false }))

答案 2 :(得分:4)

要使其与multer一起使用,您可以使用.any()(版本1.1.0)

对我而言,它的工作原理如下:(假设multer被包含并声明为“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
});

答案 3 :(得分:0)

var multer = require('multer');  
var msg = multer();  
post('/track', msg.any(), function(req, res){ 
    console.log(req.body); 
}

答案 4 :(得分:0)

当Content-type ='multipart / alternative'

时,我为req.body中的get数据创建了一个自定义解析器

https://github.com/josemadev/Multiparser/

相关问题