theStrawberryCoder
theStrawberryCoder

Reputation: 35

Why are the middlewares in app.use() not being executed

I am new in nodejs and I just started to play a little with it and middlewares, I looked at some online documentation and did the exact same thing but my middlewares are not being called, I have maximally simplified my problem, so here is the issue:

const express = require('express')

const port = 3000;
const app = express();

app.use( function(req, res, next) {
      console.log("Middeware 1 being executed");
      next();
})

app.use( function(req, res, next) {
      console.log("Middeware 2 being executed");
      next();
})

app.listen(port, () => console.log(`Listening on port: ${port}`));

But when I execute this code, in the console I can only see the "Listening on port: 3000" message, why my middlewares are not being executed, this is so weird and I am totally frustrated. Can someone explain what is going on here? Why are they not being executed at all?

Upvotes: 2

Views: 962

Answers (2)

Piyush Patel
Piyush Patel

Reputation: 1751

Middlewares are executed when requests are made. So, if you open a browser and try to open server by http://localhost:3000, you will see your two middlewares being called.

http://expressjs.com/en/guide/using-middleware.html

Good luck.

Upvotes: 0

hong4rc
hong4rc

Reputation: 4103

Open http://localhost:3000/ in your browser and you will see that logs.

Middleware will be executed by a request from the client.

Upvotes: 2

Related Questions