Facebook Messenger API:无法获取POST请求

时间:2016-04-14 05:59:05

标签: node.js facebook-messenger

我按照本页面中的步骤操作 https://developers.facebook.com/docs/messenger-platform/quickstart

我的nodejs代码

app.post('/webhook/', function(req, res) {
    messaging_events = req.body.entry[0].messaging;
    for (i = 0; i < messaging_events.length; i++) {
        event = req.body.entry[0].messaging[i];
        sender = event.sender.id;
        if (event.message && event.message.text) {
            text = event.message.text;
            sendTextMessage(sender, "Text received, echo: ");
        }
    }
    res.sendStatus(200);
});

我得到一个像这样的错误

TypeError: Cannot read property 'entry' of undefined
    at /home/user/public_html/app/testbot/webhook.js:31:30
    at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/user/public_html/app/testbot/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/home/user/public_html/app/testbot/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
    at /home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:277:22
    at Function.process_params (/home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:330:12)
    at next (/home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:271:10)
    at serveStatic (/home/user/public_html/app/testbot/node_modules/express/node_modules/serve-static/index.js:74:16)
    at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)

我无法获得来自Facebook的POST请求。我该如何解决?

1 个答案:

答案 0 :(得分:12)

我遇到了同样的问题。您需要使用body-parser lib:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
var jsonParser = bodyParser.json();

然后将其传递给post hook

app.post('/webhook/', jsonParser, function(req, res) {