【问题标题】:http request get bodyhttp请求获取正文
【发布时间】:2015-07-10 08:08:07
【问题描述】:

我是 node 的初学者,如果这个问题太明显,请原谅。我也尝试了官方文档,但我可以解决这个问题。

我的节点服务器正在通过服务与外部 api 进行通信。

这是我迄今为止在我的服务 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);

}

此时我可以获取 Json 并将其登录到控制台。但我想将返回的 json 存储在一个变量中,这样我就可以传入 next() 回调。

我尝试向结束事件添加回调,例如:

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

提前谢谢你。

【问题讨论】:

    标签: javascript json node.js http


    【解决方案1】:

    代码中回调的名称应该是“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();
    }
    

    然后你应该像这样使用你的函数:

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

    【讨论】:

      【解决方案2】:

      我可能误解了您的问题,但显而易见的解决方案是将您解析的 json 存储在一个变量中并将该变量传递给 next()

      var parsed = JSON.parse(msg);
      

      【讨论】:

      • 感谢您的回答。你能指定我应该把这行放在哪里吗,因为我在 http.request 函数中也试过这个,但是我不能在 next() 回调中使用它。
      猜你喜欢
      • 2014-06-14
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2017-01-22
      • 2020-10-04
      • 1970-01-01
      相关资源
      最近更新 更多