Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In the following code, middleware logger() is called twice if I put it as a first argument to app.use() but it doesn't get called at all if put as a second argument.

Can someone please explain what's happening?

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

app.use(express.static(path.join(__dirname,'public')), logger);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

function logger(req, res, next) {
  console.log("logger, then next");
  next();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

middleware logger() is called twice if I put it as a first argument to app.use()
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:

function logger(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.

it doesn't get called at all if put as a second argument
Because request has already been served when express reaches the logger middleware, order of middeware is very important in express.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...