[英]get url from http.get() response
I need to give my program 3 URLs than print out the server responses in the order of given URLs. 我需要给我的程序3个URL,然后按给定URL的顺序打印出服务器响应。 I need a way to see from which URL the response came, but I can't find any solution in the documentation. 我需要一种方法来查看响应来自哪个URL,但是我在文档中找不到任何解决方案。 Is there something like "response.getURL" out there? 是否有类似“ response.getURL”的内容? Thanks in advance. 提前致谢。
var strings = [];
var ended = 0;
for(int i=0; i<urls.length; i++){
http.get(urls[i], function(response){
var wholeData = "";
response.setEncoding('utf8');
response.on('error', console.error);
response.on('data', function(data){
wholeData += data;
});
response.on('end', function(){
ended ++;
strings[???] = data;
if(ended == urls.length)
printStrings();
});
});
}
You are using a single URL for an http.get()
: urls[i]
. 您正在为http.get()
使用单个URL: urls[i]
。
The response
will correspond to that urls[i]
. response
将对应于urls[i]
。
If you want to assign strings[i] = wholeData
you'll have to change how you loop because the value of i
inside that event handler will equal urls.length
. 如果要分配strings[i] = wholeData
,则必须更改循环方式,因为该事件处理程序中的i
值将等于urls.length
。 You could use a library like async
which would avoid your having to keep a request counter around and such, but if you want to keep your existing code you need to use a closure around your http.get()
to capture i
or just use urls.forEach()
: 您可以使用类似async
类的库,这样可以避免必须保留请求计数器,但是,如果要保留现有代码,则需要在http.get()
周围使用闭包来捕获i
或仅使用urls.forEach()
:
urls.forEach(function(url, i) {
http.get(url, function(response){
var wholeData = '';
response.setEncoding('utf8');
response.on('error', console.error);
response.on('data', function(data){
wholeData += data;
});
response.on('end', function(){
++ended;
strings[i] = wholeData;
if (ended === urls.length)
printStrings();
});
});
});
Or you could group your results by url instead of array index by making strings
an object and doing strings[url] = wholeData
instead. 或者,您可以通过将strings
作为对象并改为使用strings[url] = wholeData
将结果按url(而不是数组索引strings[url] = wholeData
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.