获取响应不会初始化为本地变量

时间:2015-05-28 09:00:21

标签: node.js asynchronous get

我使用以下代码从我的Android应用程序接受用户短信,并在向某个网站发出指定的获取请求后将结果发回给用户。用户应该得到的预期输出是"感谢您的消息" + [获取请求的响应] ..我得到的是"感谢您的消息未定义"似乎我的变量" body"没有使用GET response.please help

进行初始化
   var express = require('express');
   var app = express();
   app.set('port', (process.env.PORT || 5000));
   app.use(express.static(__dirname + '/public'));

   app.get('/', function(request, response) {
  response.send('Hello Cruel World!');
});

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

 var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";

 app.post('/telerivet/webhook', 
 bodyParser.urlencoded({ extended: true }),
 function(req, res) {
  var secret = req.body.secret;
  if (secret !== WEBHOOK_SECRET) {
      res.status(403).end();
      return;
  }

     if (req.body.event == 'incoming_message') {

    var content = req.body.content;
    var from_number = req.body.from_number;
    var phone_id = req.body.phone_id;
    var request = require("request");
    var body;
     request("http://www.google.com", function(error, response, data) {
   body = data;
   });
    // do something with the message, e.g. send an autoreply
    res.json({
         messages: [
        { content: "Thanks for your message! "  + body}
      ]
    });

  }  

  res.status(200).end();
 }
   );

app.listen(app.get('port'), function() {
 console.log('Node app is running on port', app.get('port'));
});

请帮我解决问题..此处发布的答案似乎无法正常工作http://goo.gl/GYgd6Z,help,请将此处指定的代码作为示例...请

1 个答案:

答案 0 :(得分:0)

res.json行将在request回调之前执行,因此不会填充正文 - 改变如下:

request("http://www.google.com", function(error, response, data) {
    // do something with the message, e.g. send an autoreply
    res.json({
        messages: [
            { content: "Thanks for your message! "  + data}
        ]
    });
    res.status(200).end();
});

这可确保在request()的响应之后执行res.json。