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"
}
}
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.