gematzab
gematzab

Reputation: 181

http request get body

I am a beginner with node so excuse me if this question is too obvious. Also I tried the official documentation but I could resolve this problem.

My node server is communicating with an external api through a service.

This is what I ve got so far in my service api-service.js :

    var http = require('http');

    exports.searchNear = function(lat, long, next){
       var options = {
           host: '1xx.xx.1xx.1x',
           path: '/api/v1/geo,
           method: 'GET'
      };

      var req = http.request(options, function(res) {
          var msg = '';

          res.setEncoding('utf8');
          res.on('data', function(chunk) {
          msg += chunk;
     });



   res.on('end', function() {
   console.log(JSON.parse(msg));
   });
   });

   req.on('error', function(err) {
     // Handle error
   });
  req.write('data');
  req.end();

  var mis = 'hello';
  next(null, mis);

}

At this moment I can get the Json and log it in the console. But I want to store the returned json in a variable so I could pass in the next() callback.

I tried to add a callback to the end event like:

     exports.searchNear = function(lat, long, next){
       ....
       .....
       var req = http.request(options, function(res) {
           .....
           res.on('end', function(callback) {
            console.log(JSON.parse(msg));
            callback(msg);
           }); 
       });
       ....
       req.end('', function(red){
       console.log(red);
       });
       }

Thank you in advance.

Upvotes: 1

Views: 3660

Answers (2)

Panos Matzavinos
Panos Matzavinos

Reputation: 86

The callback's name in your code should be "next":

var http = require('http');

exports.searchNear = function(lat, long, next) {
  var options = {
      host: '1xx.xx.1xx.1x',
      path: '/api/v1/geo,
      method: 'GET'
  };

  var req = http.request(options, function(res) {
      var msg = '';

      res.setEncoding('utf8');
      res.on('data', function(chunk) {
          msg += chunk;
      });

      res.on('end', function() {
          console.log(JSON.parse(msg));
          next(null, msg);
      });
  });

  req.on('error', function(err) {
      // Handle error
  });
  req.write('data');
  req.end();
}

And then you should use your function like this:

searchNear(myLong, myLat, function (err, mesg) {
    console.log('your JSON: ', mesg) 
});

Upvotes: 1

Anirudh Ajith
Anirudh Ajith

Reputation: 927

I may be misunderstanding your question but the obvious solution is to store your parsed json in a variable and pass the variable to next()

var parsed = JSON.parse(msg);

Upvotes: 0

Related Questions