0

myfirst.js

var http = require("http");
var firstModule = require("./myfirstExportModule");

http.createServer(function(req, res){
    res.writeHead(200, {'content-Type':'text/html'});
    res.write('first name on console. ');
    firstModule.firstname("name");
    res.end('');
}).listen(3000);

console.log("listening on port 3000...");

myfirstExportModule.js

function firstname(name){
    console.log('<br>first Name is: '+name);
}

module.exports = {
    firstname:firstname
} 

I am getting two output on console as follows

first Name is: Name
first Name is: Name

Can anyone explain why?

Hari Kishore
  • 2,201
  • 2
  • 19
  • 28
  • Hi one simple debugging way could be writing console.trace to see what is executing the console.log – Biswa Soren Mar 04 '20 at 06:44
  • 1
    Add `console.log(req.url)` to your handler and you will see the truth. Or, go look at [the question](https://stackoverflow.com/questions/58045926/express-middleware-functions-invoked-twice-when-request-is-made-from-browser) yours has been marked a dup of and it will explain there too. – jfriend00 Mar 04 '20 at 06:45
  • Other dups: [Why is request handler fired twice?](https://stackoverflow.com/questions/53036889/why-is-the-request-event-being-fired-twice/53037020#53037020), [Client is sending request twice to server](https://stackoverflow.com/questions/29555216/client-is-sending-request-twice-to-server/29555280#29555280), [Simple HTTP app responds two times](https://stackoverflow.com/questions/45888916/node-simple-http-app-respond-2-times/45888963#45888963). – jfriend00 Mar 04 '20 at 06:47

1 Answers1

1

Your one of the requests is for the favicon.ico as this is something that a browser will request when it doesn't already have a favicon cached for a particular domain.

All requests of a web server have to look at the actual resource being requested and respond appropriately based on the exact resource being requested.

If you write the code as

http.createServer(function(req, res){
    res.writeHead(200, {'content-Type':'text/html'});
    res.write('first name on console. ');
    firstModule.firstname("name");
    console.log(req.url);    // here console the requested url
    res.end('');
}).listen(3000)

then you will get

<br>first Name is: name
/
<br>first Name is: name
/favicon.ico

To defend against that, you can check request.url for a specific path and only apply your logic if the path is what you expect.

http.createServer(function(req, res){ 
 if (request.url === "/") {
  //... Do your code accordingly
 } else { 
  //....Do your code accordingly
 } 
}).listen(3000);
Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75