So i was learning Nodejs And I am confused whenever I reload my web page Why the log statements are executed two times.
The below is code written in my app.js file and whenever I reload my web page The statement present in the log get executed Two times!
const express = require('express')
const app = express();
app.use((req,res,next)=>{
console.log("in the middleware");
next();
});
app.use((req, res, next) => {
console.log("in the another middleware");
res.send('<html><title><head>document</head></title><body><p>Hello there how are you</p></body></html>')
});
app.listen(3000)
This is what I get in the terminal of the Visual studio code.
> [email protected] start D:\web development\node js
> nodemon app.js
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
in the middleware
in the another middleware
in the middleware
in the another middleware
Below is photo attached to the same :-
CodePudding user response:
This is expected behavior of expressJs framework. This is functionality of use
and next
functions.
As per your codebase:
app.use((req,res,next)=>{ // Middleware 1
console.log("in the middleware");
next();
});
app.use((req, res, next) => { // Middleware 2
console.log("in the another middleware");
res.send('<html><title><head>document</head></title><body><p>Hello there how are you</p></body></html>')
});
The middleware added using use
function, will be executed for all routes and all methods (Get, POST, PATCH, etc.). So, for any URL both of the middleware can be used to handle the request.
ExpressJs doesn't keep only one middleware for handling the network request, instead it uses Chain of Responsibility principle for handling network request.
So, when you make network request, your network request will first go to the middleware 1
(since you have added it first). You can modify the network request or send the network response based on the requirement. Since you have executed next
function, it indicates that the current middleware is not going to send the network response and the network request should be handled by next middleware in chain.
Since middleware 2
is next in chain, after middleware 1
get's executed, the control is passed to middleware 2
. Hence you can see two console.log statements.