将 request.https 响应获取到变量中

Getting the request.https response into a variable

本文关键字:变量 获取 响应 request https      更新时间:2023-09-26

今天我正在向Linode API发出这个请求。

var options = {
    hostname: 'api.linode.com',
    path: '',
    port: 443,
    method: 'GET'
}
var req = https.request(options, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(d) {
        body = JSON.parse(d.toString());
    });
    response.on('end', function() {
        console.log(body);
    });
}).end();

在此示例中,输出按预期工作。

但是,我需要将响应放入变量中,而不是将其记录到控制台。

var body = '';
var req = https.request(options, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(d) {
        body = JSON.parse(d.toString());
    });
}).end();
console.log(body);
return body;

运行上面的代码,答案总是空的,因为看起来console.log()函数或return子句没有等待请求结束。

我使用 setTimeout( function() { console.log(body); }, 2000 ) 函数解决了这个问题,但老实说,不能将其视为有效的解决方案,因为每个请求的超时都会有所不同。

我尝试的其他解决方案是while (!req.finished) {} console.log(body);,但它也没有按预期工作。

最后,我尝试添加以下内容:

response.on('end', function() {
    return body;
});

但也没有成功:(

也就是说,您是否有任何建议让此函数在返回 body 变量的值之前等待请求超时?

最简单的方法是将代码放在一个接受(至少)回调的函数中。您还需要缓冲来自所有data事件的数据,因为您不能假设只有一个事件。例:

// you may want to add other parameters too depending on your needs of course ...
function linodeReq(cb) {
  var options = {
    hostname: 'api.linode.com',
    path: '',
    port: 443,
    method: 'GET'
  }
  https.get(options, function(response) {
    var buffer = '';
    response.on('data', function(d) {
      buffer += d;
    }).on('end', function() {
      var body;
      try {
        body = JSON.parse(buffer)
      } catch (err) {
        return cb(err);
      }
      cb(null, body);
    }).setEncoding('utf8');
  });
}
// then use it like ...
linodeReq(function(err, result) {
  // check for `err` first ...
});

您还应该处理请求(和response)对象上的error事件,并在发生时将它们传递给回调。例如,如果无法解析主机名或出现其他连接错误,则可能会发生这种情况。