Eliya Eliya - 5 months ago 11
Javascript Question

chrome browser shows counting error for nodejs code

I wrote some nodejs code. In execution, I noticed that the chrome browser for the first visit shows the count with value 1 then for the visit after, it shows 3, 5, 9 and so on. the Internet explorer browser works fine, I mean, it shows 1, 2, 3 and so on. I don't understand the reason of it. The code I wrote is attached below. Where is the mistake in my code?

Thanks for any help.

var http = require('http');
var socket = require('socket.io')();
var port = process.env.port || 1337;
var count = 0;
var x = 0;
socket.on('connection', function (client) {
count++;
console.log("soc con");
client.broadcast({ count: count })
client.on('disconnect', function () {
count--;
console.log("soc dis");
});
console.log(count);
})

http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
count++;
var c = count.toString();
res.end(c);
}).listen(port);

Answer

When browsers connect to a web page, they will often request the page you ask for AND they will request the icon for the page (called the favicon). That's two requests to the same server. If you add:

console.log(req.url);

to your server handler, you will see that you are getting two requests for each browser page, one for the URL of the page and one for a page icon (often called the favicon). If you want to ignore the page icon request, you can add an if block like this if (req.url === "/") { code here} to avoid any other URL requests and only increment your counter for specific pages.

How exactly the page icon is requested is browser-specific so it is certainly possible that IE might behave differently than Chrome in this case.

Change your server to this:

http.createServer(function (req, res) {
    if (req.url === '/') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        count++;
        res.end(count);
    } else {
        res.statusCode = 404;
        res.end();
    }
}).listen(port);

FYI, you can replace this:

var c = count.toString();
res.end(c);

with this:

res.end(count);

In Javascript, string conversions happen automatically.