node.jsasynchronousget

Get Response Doesnt Initialize to a local variable


I use the following code to accept the user sms from my android app and send back the result to the user after making specified get request to some site.the expected output that the user should get is "thanks for your message"+[the response of get request]..what i get is "Thanks for your message undefined"it seems that my variable "body" doesnt get initialized with the 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'));
});

please help me to resolve the problem..the answer posted here doesnt seems working, help by taking my code specified here as example


Solution

  • The res.json line will execute before the callback from request, so body won't be populated - change like this:

    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();
    });
    

    This ensures that the res.json is executed after the response from request().