Node.js 节点http.get未被激发
我试图使用http.get请求进行循环,但我不知道为什么该函数不能启动。 我的代码是:Node.js 节点http.get未被激发,node.js,httprequest,Node.js,Httprequest,我试图使用http.get请求进行循环,但我不知道为什么该函数不能启动。 我的代码是: while(List.length>0) { if(counter < Limit) { // Limit is the amount of requests I want to counter++; inProcess++; var scanitem = List.pop(); var bod
while(List.length>0) {
if(counter < Limit) { // Limit is the amount of requests I want to
counter++;
inProcess++;
var scanitem = List.pop();
var body = "";
var url = 'https://www.mywebsite.com/'+scanitem;
var options = {
path: url,
method: 'GET'
};
console.log(url); // This part is happenning
var _request = https.get(options, function (res) {
console.log('get web site');// this part is NOT showup.
res.on('data', function (chunk) {
console.log(chunk); // this part is NOT showup.
body += chunk.toString();
});
res.on("end", function() {
console.log(body);// this part is NOT showup.
});
res.on("error", function(error) {
console.log('error')// this part is NOT showup.
});
});
_request.end();
}
else {
console.log('list BREAK');} // This part is happenning after the limit crossed
while(List.length>0){
if(counter
对象
作为第一个参数传递时,URL应分解为各个部分:
var options = {
method: 'GET',
protocol: 'https:',
hostname: 'www.mywebsite.com',
path: '/' + scanitem
};
var _request = https.get(options, ...);
下面介绍了使用的选项,其中https.get()
是的一个方便变体
您还可以传递URLString
,该URLhttps.get()
将为您运行:
var body=“”;
,但是循环的每次迭代都会附加到相同的body
当变量仅由同步任务使用时,如scanitem
、url
和选项
,这一点就不那么重要了。但是,当混合在异步任务(如https.get()
)中时,您可能不会得到预期的结果
在当前没有块作用域变量的情况下,可以使用来创建附加的函数
作用域
由于列表
似乎是一个数组
,因此可以使用迭代器函数
来实现此目的:
List.forEach(function (scanitem) {
var body = '';
var url = 'https://www.mywebsite.com/'+scanitem;
https.get(url, function (res) {
// etc.
});
});
并且,对于限制
,您可以使用.splice()
删除并使用所需的阵列部分
:
List.splice(0, Limit).forEach(function (scanitem) {
// etc.
});
另外,与使用
https.request()
不同,当使用https.get()
时,您不需要调用\u request.end()
,当我将它从循环中取出时,它工作正常,但当它是流程的一部分时,它不知何故不会启动请求。您可以首先添加\u request.on(“错误”,函数(错误)
查找任何错误。由于在发送任何响应之前,请求本身可能会失败,因此不会显示任何响应错误。https请求可能需要密钥或证书。由于您没有提供任何服务器,因此可能会拒绝请求本身。
List.splice(0, Limit).forEach(function (scanitem) {
// etc.
});