如何从Node.js的http get请求中获取数据
我试图让我的函数返回http get请求,但是,无论我怎么做,似乎都会在 "范围 "中丢失。我是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);
}
73
3
当然,你的日志会返回
undefined
:你在请求完成之前就进行了记录。问题不在于范围,而在于同步性。http.request
是异步的,这就是为什么它需要一个回调作为参数。在回调中做你必须做的事情(你传递给response.end
的那个):来自Learnnyounode:
'options'是主机/路径变量
这是我的解决方案,尽管你肯定可以使用很多模块,把对象作为一个承诺或类似的东西给你。总之,你缺少另一个回调
在其他地方