简体   繁体   中英

Trying to guess code from body-parser and Node.js

So I'm just starting and fairly new with Node.js & Express, but I'm following this tutorial https://github.com/jw84/messenger-bot-tutorial , and I understand most of it, but, from the following code:

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: " + text.substring(0, 200))
    }
}
res.sendStatus(200)

I don't understand what "entry" and "messaging" do or where do they come from in req.body.entry[0].messaging

entry and messaging are coming from the JSON in the POST request. On line 12 of the tutorial ( https://github.com/jw84/messenger-bot-tutorial/blob/master/index.js#L12 ) you can see the author parses the incoming request body for JSON. That JSON is added onto the body property of the incoming request. So in short, it's specific to his example. If the incoming request looked like this:

{ data: ["messaging": "hi"], ["messaging": "bye"] }

then entry would instead need to be changed to data .

Additionally you can see this is part of the messenger specification in Facebook's docs: https://developers.facebook.com/docs/messenger-platform/quickstart#receive_messages

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM