Node.js http get example does not work here is fix

Many of us has tried the node.js example how to make HTTP get request. Only problem is that it does not get you the correct google web page as it returns the HTTP code 302. This means that the site has to redirected to other site, which is basically mapped by your IP local site google.ee (estonia) or google.fi (finland). That is the reason why the first request fails in node, I made simple workaround for this.

var http = require('http')
  , url = require('url');

function request(address) {
	http.get({ host: address, path: '/index.html'}, function(response) {
		// The page has moved make new request
		if (response.statusCode === 302) {
			var newLocation = url.parse(response.headers.location).host;
			console.log('We have to make new request ' + newLocation);
			request(newLocation);
		} else {
			console.log("Response: %d", response.statusCode);
			response.on('data', function(chunk) {
				console.log('Body ' + chunk);
			});
		}
	}).on('error', function(err) {
		console.log('Error %s', err.message);
	});
}

request('www.google.com');

Making google search

var http = require('http')
  , url = require('url');

function request(address, path) {
	http.get({ host: address, path: path}, function(response) {
		// The page has moved make new request
		if (response.statusCode === 302) {
			var newLocation = url.parse(response.headers.location).host;
			console.log('We have to make new request ' + newLocation);
			request(newLocation);
		} else {
			console.log("Response: %d", response.statusCode);
			response.on('data', function(chunk) {
				console.log('Body ' + chunk);
			});
		}
	}).on('error', function(err) {
		console.log('Error %s', err.message);
	});
}

request('www.google.com', '/search?ie=UTF-8&q=node');

One thought on “Node.js http get example does not work here is fix

  1. You should store the request object at line 5 and call req.abort(); at line 10, otherwise the request object stays open until it times out… (it did for me anyway)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s