在函数外声明变量

时间:2018-06-29 00:55:49

标签: javascript node.js express facebook-messenger facebook-messenger-bot

sender_psid在app.post函数内部声明。有没有一种方法可以声明它,以便底部的函数调用可以访问它?

注意:在函数外部声明它没有帮助,因为webhook.event在函数外部不存在。

/ Creates the endpoint for our webhook
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 - there may be multiple if batched
    body.entry.forEach(function(entry) {

    // Gets the body of the webhook event
    let webhook_event = entry.messaging[0];
    console.log(webhook_event);


    // Get the sender PSID
    let sender_psid = webhook_event.sender.id;
    console.log('Sender PSID: ' + sender_psid);

    // Check if the event is a message or postback and
    // pass the event to the appropriate handler function
    if (webhook_event.message) {
      msg.handleMessage(sender_psid, webhook_event.message);
    } else if (webhook_event.postback) {
      msg.handlePostback(sender_psid, webhook_event.postback);
    }


  });

    // Returns a '200 OK' response to all requests
    res.status(200).send('EVENT_RECEIVED');
  } else {
    // Returns a '404 Not Found' if event is not from a page subscription
    res.sendStatus(404);
  }

});
//Imports functions from other files
let  msg = require('./msg.js'),
     handleMessage = msg.handleMessage(sender_psid, received_message),
     handlePostback = msg.handlePostback(sender_psid, received_postback),
     callSendAPI = msg.callSendAPI(sender_psid, response);

1 个答案:

答案 0 :(得分:3)

您再也不需要node.js服务器中特定于请求的全局变量。这仅允许不同的请求删除其他请求尝试使用的值。如果您的请求处理程序中有任何异步操作,则可能是并发错误或竞争条件的一种形式。不要做。不要尝试这样做。这是一个糟糕的设计。

相反,您有以下选择:

  1. 将来自请求处理程序的所有数据作为函数参数传递给外部函数。
  2. 将数据作为属性添加到reqres对象(总是特定于请求)中,然后将该reqres对象传递给外部对象功能,以便它可以在那里访问数据。
  3. 将数据作为属性添加到您在该请求处理程序中专门创建的其他对象中,然后将该对象传递给外部函数,以便它可以在那里访问数据。

如果您尝试在请求处理程序中创建一些数据,然后在以后的请求处理程序中访问该数据,则可以使用Cookie或会话来保存该数据,然后再访问它将来来自同一客户的请求。