Search code examples
javascriptnode.jsexpressmiddleware

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

Solution

  • app.use is running every time you trigger app. in this case you trigger twice. app.get and app.listen