Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...