简体   繁体   English

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

[英]How to get host name in http response in node.js?

I am using http module of node.js for making a request. 我正在使用node.js的http模块发出请求。 I have bunch of urls in database. 我在数据库中有一堆网址。 I am fetching these urls from database and making requests in loop. 我正在从数据库中获取这些URL,并在循环中发出请求。 But when response comes, I want to get host name of that response, because I want to update something in database based on that response. 但是,当响应到来时,我想获取该响应的主机名,因为我想基于该响应来更新数据库中的某些内容。 But I am not getting for which site I am getting response, so I am unable to update record for that site. 但是我没有得到哪个站点的响应,因此无法更新该站点的记录。

Code is something like this: 代码是这样的:

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;
        }
    });
}

Option one : use res.req 选项一 :使用res.req

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

Option two : use a closure 选择二 :使用闭包

for (site = 0; site < no_of_sites; site++) {
    (function(){
        var options = {
            // ...
        };

        var req = http.request(options, function (res) {
            // options available here
            console.log(options);
        });
    }());
}

Option three : 选项三

It seems this is the same as res.req in the http.request() callback, but I'm not completely sure. 看来this是一样的res.reqhttp.request()回调,但我不能完全肯定。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM