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

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

javascript - ExpressJS middleware is being called twice

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...