12

When this code is run, i is incremented by two every time and I can't pinpoint in the documentation or otherwise why this would be the case. I'd expect the increment to be by one for each request, but it's not. Why is this behaving the way it is?

var http = require('http');
var i = 0;
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Number: ' + i + '\n');
  i++;
}).listen(8000, '127.0.0.1');
Matty
  • 33,203
  • 13
  • 65
  • 93
  • Just to confirm, are you using Chrome? Have you tried another browser? I suspect it won't happen in Firefox (for example), see my comment on Raynos's answer. – Luke Girvin Oct 26 '11 at 15:28

1 Answers1

29

console.log(req.url);

You will notice the urls are / and /favicon.ico

Browsers like making requests to favicon.ico for you. That's why you get 2 requests.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • This is probably due to a bug in Chrome, see this answer: http://stackoverflow.com/questions/4761913/server-socket-receives-2-http-requests-when-i-send-from-chrome-and-receives-one/4941800#4941800 – Luke Girvin Oct 26 '11 at 15:27
  • @LukeGirvin Yup, Chrome. Only increments by two on the first occasion, and every time after that it's a single increment. I didn't think of the favicon issue. – Matty Oct 26 '11 at 15:41
  • Oh, I also noticed that issue when I first got into Node.js. Thanks for the answer Raynos! – David Da Silva Contín Aug 04 '12 at 11:06
  • @Raynos I got exactly the same issue here! +1 for Firefox and +2 for Chrome. Thanks! – wesley.mesquita Jan 24 '14 at 15:41
  • Jeez man, why I keep finding your answers to my questions! Apparently Chrome does not show favicon request in Develoer -> Network, that is misleading. – alandarev Oct 02 '14 at 16:11