我正在为Facebook Messenger平台的聊天机器人工作,我发现了一个让我发疯的问题,因为我无法弄清楚为什么这是一个问题。
此代码正常运行。
app.post('/webhook', (req, res) => {
let body = req.body;
// Checks this is an event from a page subscription
if (body.object === 'page') {
// Iterates over each entry
body.entry.forEach(function(entry) {
// Gets the body of the webhook event
let webhookEvent = entry.messaging[0];
console.log(webhookEvent);
});
res.status(200).send('EVENT_RECEIVED');
}
else {
// Returns a '404 Not Found'
res.sendStatus(404);
}
});
但最初,我想让function(entry)
中的forEach
成为 ES6箭头功能,例如:
body.entry.forEach((entry) => {
// Gets the body of the webhook event
let webhookEvent = entry.messaging[0];
console.log(webhookEvent);
});
但登录控制台指出了这一点:
at body.entry.forEach (/app/src/app.js:57:41)
2017-12-19T15:10:08.768620+00:00 app[web.1]: TypeError: Cannot read property '0' of undefined
2017-12-19T15:10:08.768631+00:00 app[web.1]: at Array.forEach (<anonymous>)
2017-12-19T15:10:08.768632+00:00 app[web.1]: at app.post (/app/src/app.js:54:17)
2017-12-19T15:10:08.768634+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-12-19T15:10:08.768636+00:00 app[web.1]: at next (/app/node_modules/express/lib/router/route.js:137:13)
2017-12-19T15:10:08.768637+00:00 app[web.1]: at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
2017-12-19T15:10:08.768638+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-12-19T15:10:08.768638+00:00 app[web.1]: at /app/node_modules/express/lib/router/index.js:281:22
2017-12-19T15:10:08.768639+00:00 app[web.1]: at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12)
2017-12-19T15:10:08.768640+00:00 app[web.1]: at next (/app/node_modules/express/lib/router/index.js:275:10)
为什么这不适用于ES6箭头功能?