Strange problem with Node.js http server

As I was experimenting with the node.js http module, I observed that the server was hit twice for each request I was making. For example, the following example returns a counter to the browser. The first time I accessed I got the value of counter as 2. But for each browser refresh, I got the value incremented by 2. Strange, isn’t it?

 

var http = require("http");
var num = 1;
var server = http.createServer(function(req, resp){
	num++;
	resp.writeHead(200, {
		"Content-type": "text/plain"
	});
	resp.end("Hello, user! The value of num = " + num);
});

server.listen(3000);
console.log("Server listening at port 3000");

 

Finally, after few attempts, I realized that the browser (Google Chrome) was hitting the server twice: once for the “/” and again for “/favicon.ico”.

So, the modified version of the above code looks like this:

var http = require("http");
var num = 1;
var server = http.createServer(function(req, resp){
	if(req.url!="/favicon.ico"){
		num++;
		resp.writeHead(200, {
			"Content-type": "text/plain"
		});
		resp.end("Hello, user! The value of num = " + num);
	}
});

server.listen(3000);
console.log("Server listening at port 3000");

In most cases, the response to the client generally depends on the URL (for example for REST api), and hence this problem may not arise.

I hope this would help you guys, as it did to me.

Vinod.