1

I don't understand why is my code logging messages two times when I'm just creating only one server and loading it once in the browser.

INPUT -

const express = require('express');

const app = express();

app.use((req, res, next) => {
    console.log('Hello middleware')
    next(); // Allows the request to continue to the next middleware in line
});

app.use((req, res, next) => {
    console.log('Hello middleware v2')
    res.send('<h1>Hello Express!</h1>');
});

app.listen(3000);

OUTPUT -

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Hello middleware
Hello middleware v2
Hello middleware
Hello middleware v2

package.json -

{
  "name": "nodeproject1",
  "version": "1.0.0",
  "description": "node tutorial",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "Arkapratim Sarkar",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^2.0.6"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}
Arka
  • 957
  • 1
  • 8
  • 18
  • How do you invoke the request ? Add some more debug information to the `console.log`, like source port & ip. So you can see if they are multiple requests or there is another problem – Marc Nov 25 '20 at 11:33
  • 1
    as i mentioned by 'app.listen(3000);' and going to 'localhost:3000'. anyway @eol pointed out that a default icon file is also making a request thus the double logging – Arka Nov 25 '20 at 11:54

1 Answers1

2

If you perform the request through your browser not only will a request be sent for the corresponding request-path (e.g./) but also for /favicon.ico (details are explained here). Since two requests are made, you see each of your middleware's log message twice.

eol
  • 23,236
  • 5
  • 46
  • 64
  • 1
    thanks for explaining this. I've been seeing this '/favicon.ico' in network tab of dev tools but didn't think that it is also making a different request. – Arka Nov 25 '20 at 11:42