Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express middleware gets called multiple times

My middlewares are getting called multiple times and I can't figure out why. It's a really short code and it is very frustrating as I just started learning express and node. I don't understand why it's even getting into the second middleware, I didn't use next(), I used res.send().

I am taking an online course and it's the same code as it is described. I also searched stackoverflow but nothing helped. I did read something about the favicon that calls it a second time, but I can't figure out why this is getting called multiple times.

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

app.use("/", (req, res, next) => {
    console.log("This always runs!");
    next();
});

app.use("/add-product", (req, res, next) => {
    console.log("In first middleware!");
    res.send("<h1>Add Product</h1>");
});

app.use("/", (req, res, next) => {
    console.log("In second middleware!");
    res.send("<h1>Hello from express!</h1>");
});

app.listen(3000);

If I'm opening localhost:3000/add-product I should get in the console:

This always runs!
In first middleware!

but I actually get:

This always runs!
In first middleware!
This always runs!
In second middleware!
This always runs!
In first middleware!

Could it be that the favicon automatically executes all middlewares once? I added this code before the first app.use() call:

app.get("/favicon.ico", (req, res) => res.status(204));

Now I get

This always runs!
In first middleware!
This always runs!
In first Middleware!

I still get it twice.

edit edit edit:

This appears only to happen in chrome.

like image 446
Mario Hess Avatar asked Aug 09 '26 20:08

Mario Hess


1 Answers

Don't use app.use for routes that's mainly used for middleware registration you want to use the router. https://expressjs.com/en/4x/api.html#app.use

app.(post|get|delete|put)("route", function(req,res,next){})

in your case it's best to see if your browser is requesting 2 http calls. If so it'll double up.

like image 65
Andrei Avatar answered Aug 12 '26 09:08

Andrei



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!