[英]How to get data out of a Node.js http get request
I'm trying to get my function to return the http get request, however, whatever I do it seems to get lost in the ?scope?. 我正在尝试让我的函数返回http get请求,但是,无论如何,它似乎在?scope中丢失了。 I'm quit new to Node.js so any help would be appreciated 我对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);
}
Of course your logs return undefined
: you log before the request is done. 当然,您的日志返回的是undefined
:您在请求完成之前登录。 The problem isn't scope but asynchronicity . 问题不是范围,而是异步性 。
http.request
is asynchronous, that's why it takes a callback as parameter. http.request
是异步的,这就是为什么它将回调作为参数的原因。 Do what you have to do in the callback (the one you pass to response.end
): 做您在回调中要做的事情(传递给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();
Shorter example using http.get: 使用http.get的简短示例:
require('http').get('http://httpbin.org/ip', (res) => {
res.setEncoding('utf8');
res.on('data', function (body) {
console.log(body);
});
});
from learnyounode: 来自learnyounode:
var http = require('http')
http.get(options, function (response) {
response.setEncoding('utf8')
response.on('data', console.log)
response.on('error', console.error)
})
'options' is the host/path variable 'options'是主机/路径变量
from learnyounode: 来自learnyounode:
var http = require('http')
var bl = require('bl')
http.get(process.argv[2], function (response) {
response.pipe(bl(function (err, data) {
if (err)
return console.error(err)
data = data.toString()
console.log(data)
}))
})
This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. 这是我的解决方案,尽管可以肯定的是,您可以使用很多模块来使对象成为一个承诺或类似对象。 Anyway, you were missing another callback 无论如何,您错过了另一个回调
function getData(callbackData){
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);
callbackData(str);
});
//return str;
}
var req = http.request(options, callback).end();
// These just return undefined and empty
console.log(req.data);
console.log(str);
}
somewhere else 别的地方
getData(function(data){
// YOUR CODE HERE!!!
})
I think it's too late to answer this question but I faced the same problem recently my use case was to call the paginated JSON API and get all the data from each pagination and append it to a single array. 我认为现在回答这个问题为时已晚,但是最近我遇到了同样的问题,我的用例是调用分页JSON API,并从每个分页中获取所有数据并将其附加到单个数组中。
const https = require('https');
const apiUrl = "https://example.com/api/movies/search/?Title=";
let finaldata = [];
let someCallBack = function(data){
finaldata.push(...data);
console.log(finaldata);
};
const getData = function (substr, pageNo=1, someCallBack) {
let actualUrl = apiUrl + `${substr}&page=${pageNo}`;
let mydata = []
https.get(actualUrl, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', async () => {
if (JSON.parse(data).total_pages!==null){
pageNo+=1;
somCallBack(JSON.parse(data).data);
await getData(substr, pageNo, someCallBack);
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
getData("spiderman", pageNo=1, someCallBack);
Like @ackuser mentioned we can use other module but In my use case I had to use the node https
. 就像提到的@ackuser一样,我们可以使用其他模块,但是在我的用例中,我必须使用节点https
。 Hoping this will help others. 希望这对别人有帮助。
Simple Working Example of Http request using node. 使用节点的Http请求的简单工作示例。
const http = require('https')
httprequest().then((data) => {
const response = {
statusCode: 200,
body: JSON.stringify(data),
};
return response;
});
function httprequest() {
return new Promise((resolve, reject) => {
const options = {
host: 'jsonplaceholder.typicode.com',
path: '/todos',
port: 443,
method: 'GET'
};
const req = http.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
var body = [];
res.on('data', function(chunk) {
body.push(chunk);
});
res.on('end', function() {
try {
body = JSON.parse(Buffer.concat(body).toString());
} catch(e) {
reject(e);
}
resolve(body);
});
});
req.on('error', (e) => {
reject(e.message);
});
// send the request
req.end();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.