Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs with express : Why my middleware is executing twice Here is the code

This is my code here..!

const express = require('express');
const app = express();

let myFunc = function (req, res, next) {
    console.log('This is middleware');
    next();
}

app.use(myFunc);

app.get('/', (req, res) => {
    console.log('This is get /');
    res.send('Hello World!');
});

app.listen(3000, () => {
    console.log('Server is running at port 3000....');
});

In this I have created a middleware called myFunc but the output is not as I thought it would be

Server is running at port 3000....
This is middleware
This is get /
This is middleware
like image 754
Aditya Pradhan Avatar asked May 15 '26 12:05

Aditya Pradhan


1 Answers

This happens because the browser is requesting two files. The first will be for / and the second is likely for favicon.ico. If you want to see why this is being called change your one function to look like this:

let myFunc = function (req, res, next) {
  console.log('This is middleware', req.originalUrl);
  next();
}

Then it will output the URL that was requested for each time the browser hits the server.

like image 57
Intervalia Avatar answered May 18 '26 00:05

Intervalia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!