简体   繁体   English

HTTP请求获取正文

[英]http request get body

I am a beginner with node so excuse me if this question is too obvious. 我是node的初学者,所以如果这个问题太明显,请原谅。 Also I tried the official documentation but I could resolve this problem. 我也尝试了官方文档,但可以解决此问题。

My node server is communicating with an external api through a service. 我的节点服务器正在通过服务与外部api通信。

This is what I ve got so far in my service api-service.js : 到目前为止,这是我在服务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. 此时,我可以获取Json并将其记录在控制台中。 But I want to store the returned json in a variable so I could pass in the next() callback. 但是我想将返回的json存储在一个变量中,以便可以传递next()回调。

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": 您代码中的回调名称应为“ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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