简体   繁体   中英

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.

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

我可能会误解您的问题,但显而易见的解决方案是将已解析的json存储在变量中,然后将变量传递给next()

var parsed = JSON.parse(msg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM