Wednesday, 15 March 2017

http.get will return 301 status code because of host variable in Node.js

By following my code below:

var http = require('http');

var options = {
    host: 'www.stackoverflow.com',
    path: '/',
    method: 'GET'
};

http.get(options, function(res) {
    console.log("Status Code: " + res.statusCode);
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

I'm trying to get status code by sending request to different addresses using http module in Node.js, I noticed that when I fill host variable by 'http://' I will get this error

Got error: getaddrinfo ENOTFOUND

and that's because host is not the same as URL and I should write the address either by using 'www.' or simply put 'stackoverflow.com' in host variable.

but here is my problem, when I try to fill host variable by 'www.' some hosts like 'www.stackoverflow.com' will return 301 status code and some like 'www.google.com' will return 200.

and in opposite, when I put 'stackoverflow.com' without 'www.' into host variable, I get 200 status code and by writing 'google.com' I get 301 status code.

so why is it? I can't change given hosts based on results every time. is there a way to write the hosts address so that I always get the 200 status code?



via Brian SP

No comments:

Post a Comment