DrunkenMaster
DrunkenMaster

Reputation: 1278

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?

Upvotes: 0

Views: 93

Answers (2)

DanielKhan
DanielKhan

Reputation: 1208

This can be traced down by logging out req using console.log(req).

Looking at the raw request we see that the browser additionally requests /favicon for each request.

url: '/',
url: '/favicon.ico',

Upvotes: 2

DrakaSAN
DrakaSAN

Reputation: 7873

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.

Upvotes: 3

Related Questions