如何在node.js的http响应中获取主机名?

我正在使用node.js的http模块来提出请求。 我有一堆的数据库中的url。 我正在从数据库中获取这些url,并在循环中发出请求。 但是,当响应来了,我想获得该响应的主机名,因为我想根据该响应更新数据库中的东西。 但我没有得到哪个网站得到回应,所以我无法更新该网站的logging。

代码是这样的:

for (site = 0; site < no_of_sites; site++) { options = { hostname: sites[site].name, port: 80, method: 'GET', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0' } }; var req = http.request(options, function (res) { console.log('HEADERS: ' + JSON.stringify(res.headers)); if (res.statusCode == 200) { //Update record; } }); } 

我们可以在this对象中获得主机站点。

 console.log(this._header.match(/Host\:(.*)/g)); 

选项一 :使用res.req

 var req = http.request(options, function (res) { console.log(res.req._headers.host) }); 

选项二 :使用闭包

 for (site = 0; site < no_of_sites; site++) { (function(){ var options = { // ... }; var req = http.request(options, function (res) { // options available here console.log(options); }); }()); } 

scheme三

看起来thishttp.request()callback中的http.request()是一样的,但我不完全确定。

答案是console.log(res.socket._httpMessage._headers.host);