问题
Below is my nodejs code
const express = require('express');
const app = express();
app.use('/', (req, res, next) => {
console.log("In interceptor");
next();
});
app.use('/users', (req, res, next) => {
console.log('In /users middleware');
res.send('<h1>From "/users" handler </h1>');
});
app.use('/', (req, res, next) => {
console.log("Default handler");
res.send('<h1>From default handler</h1>');
});
app.listen(3000);
Console output when a request is made from browser (both chrome and edge)
http://localhost:3000
******************
In interceptor
Default handler
In interceptor
Default handler
******************
http://localhost:3000/users
******************
In interceptor
In /users middleware
In interceptor
Default handler
******************
But when a request is made using curl
, I don't see multiple invocations
curl http://localhost:3000
******************
In interceptor
Default handler
******************
curl http://localhost:3000/users
******************
In interceptor
In /users middleware
******************
Can someone explain why middleware functions are invoked multiple times when request is made from browser?
回答1:
The usual reasons you see multiple requests when a page loads from a browser are one of two things:
- The browser automatically requesting the favicon.ico file.
- The browser attempting to load some resource from the HTML file (script file, image, CSS file, etc..)
You can see exactly what each request is for by adding:
console.log(req.url);
to your middleware.
回答2:
Found that it is happening due to /favicon.ico
request made by browser. Adding specific handler (shown below) prevented default handler from being called twice
app.use('/favicon.ico', (req, res, next) => {
console.log('favicon handler');
res.sendStatus(200);
});
来源:https://stackoverflow.com/questions/58045926/express-middleware-functions-invoked-twice-when-request-is-made-from-browser