下面是我的nodejs代码
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);
从浏览器(Chrome 和 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
******************
但是当使用 curl
发出请求时,我没有看到多次调用
curl http://localhost:3000
******************
In interceptor
Default handler
******************
curl http://localhost:3000/users
******************
In interceptor
In /users middleware
******************
有人可以解释为什么当浏览器发出请求时中间件函数会被多次调用吗?
最佳答案
从浏览器加载页面时看到多个请求的常见原因有以下两种:
- 浏览器自动请求 favicon.ico 文件。
- 浏览器尝试从 HTML 文件(脚本文件、图像、CSS 文件等)加载某些资源
您可以通过添加以下内容来准确查看每个请求的用途:
console.log(req.url);
到您的中间件。
关于node.js - 当浏览器发出请求时,express 中间件函数被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045926/