1

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

3 Answers 3

2

We can get host site in this object.

console.log(this._header.match(/Host\:(.*)/g));
Sign up to request clarification or add additional context in comments.

Comments

2

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 completely sure.

2 Comments

thanks for answering, though your answer doesn't worked, it lead me to answer after some experimenting.
@sushant Really? What worked for you then? I'd like to improve my answer if it is not correct
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.