user3796318 user3796318 - 1 month ago 8
HTTP Question

Why two times the callback invoked in CreateServer of http in nodejs

i am trying with following code:

const http = require('http');
const fs = require('fs');


var hServer = http.createServer( (req, res) => {
console.log ("Received Connection..");
fs.readFile('./index.html', function(err, page) {
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(page);
res.end();

});
});

hServer.listen(8989);


When i connect from browser http://localhost:8989,

I received two times the console print "Received Connection." Why?

Answer
const  http = require('http');
const fs = require('fs');


var hServer = http.createServer( (req, res) => {
        console.log ("Received Connection...");
        console.log('URL: ' + req.url);
        fs.readFile('./index.html', function(err, page) {
                res.writeHeader(200, {"Content-Type": "text/html"});
                res.write(page);
                res.end();

        });
});

hServer.listen(8989);

Will print:

Received Connection...
URL: /
Received Connection...
URL: /favicon

It is because the browser automatically ask for the favicon, the little icon you see in your tabs. If you fire your request from POSTMan, wget, curl, or other http tools, you'll only see one request.

Comments