最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get host name in http response in node.js? - Stack Overflow

programmeradmin2浏览0评论

I am using http module of node.js for making a request. I have bunch of urls in database. I am fetching these urls from database and making requests in loop. But when response es, 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;
        }
    });
}

I am using http module of node.js for making a request. I have bunch of urls in database. I am fetching these urls from database and making requests in loop. But when response es, 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;
        }
    });
}
Share Improve this question edited Sep 25, 2013 at 11:27 Andreas Hultgren 15k4 gold badges46 silver badges48 bronze badges asked Sep 25, 2013 at 11:03 sushantsushant 811 gold badge3 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

We can get host site in this object.

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

Option one: use 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 pletely sure.

The answer is console.log(res.socket._httpMessage._headers.host);

发布评论

评论列表(0)

  1. 暂无评论