如何从Node.js http获取请求中获取数据
我正在尝试让我的函数返回http get请求,但是,无论如何,它似乎在?scope中丢失了。我对Node.js不熟悉,因此不胜感激
function getData(){  var http = require('http');
  var str = '';
  var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
  };
  callback = function(response) {
        response.on('data', function (chunk) {
              str += chunk;
        });
        response.on('end', function () {
              console.log(str);
        });
        //return str;
  }
  var req = http.request(options, callback).end();
  // These just return undefined and empty
  console.log(req.data);
  console.log(str);
}
回答:
当然,您的日志会返回undefined:您在完成请求之前先进行日志。问题不是范围,而是 异步性 。
http.request是异步的,这就是为什么它将回调作为参数的原因。做您在回调中要做的事情(传递给的response.end):
callback = function(response) {  response.on('data', function (chunk) {
    str += chunk;
  });
  response.on('end', function () {
    console.log(req.data);
    console.log(str);
    // your code here if you want to use the results !
  });
}
var req = http.request(options, callback).end();
以上是 如何从Node.js http获取请求中获取数据 的全部内容, 来源链接: utcz.com/qa/412233.html
