I'm learning Node.js and I'd like to understand the "why" when code spits out duplicated console.log outputs but only a single response.write outputs.
Heres my simple code example:
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-type': 'text/plain'});
console.log('hello 1');
response.write('Hello world');
console.log('hello 2');
response.end();
}).listen(8000);
And on my console/terminal I get:
hello 1
hello 2
hello 1
hello 2
Thanks.
Some browsers also send a request to locate the favicon.ico file. Since the file isn't present by default, a browser(Chrome in particular) will always send two requests: one for the originally requested file and another for favicon.ico. This is a known bug in Chrome and has been fixed in version 29. Firefox, however, requests for favicon.ico only for the first request. If you console.log
the request URI path, you must see a request to localhost:8000/favicon.ico.
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-type': 'text/plain'});
if(request.url === '/favicon.ico') {
console.log('Favicon was requested');
}
console.log('hello 1');
response.write('Hello world');
console.log('hello 2');
response.end();
}).listen(8000);
I've had the same problem myself, and I found out that using something like
var http = require('http');
http.createServer(function(req,res) {
if(req.url === '/favicon.ico')
{
//everything here is ignored
}
res.writeHead(200,{"Content-Type": "text/plain"});
res.write("Hello World\n");
res.end();
console.log("Connection made");
}).listen(1337, "127.0.0.1");
console.log("Server running at http://127.0.0.1:1337/");
is enough to avoid that behaviour. For some reason, when I check req.url and compare it to '/favicon.ico'
nothing is sent to console, in fact, everything in that block is ignored. I don't know if this behaviour is expected, but you sure could try it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With