我正在使用 Nodejs 并使用expressjs,现在我正在研究中间件功能,我想知道中间件概念中的“下一个”工作是什么? “下一个进入下一个中间件”,但是什么是“下一个中间件”?我尝试使用以下代码,每当我点击“http://localhost:3000/”,然后在控制台和浏览器中显示“中间件 1 和中间件 2” 总是显示“hello world”,所以“下一个中间件”总是意味着“路由器处理程序”(get 方法)?
const express = require('express');
const app = express();
// Middleware function 1
app.use((req, res, next) => {
  console.log('Middleware 1');
  next(); // Move to the next middleware
});
// Middleware function 2
app.use((req, res, next) => {
  console.log('Middleware 2');
  next(); // Move to the next middleware
});
// Route handler
app.get('/', (req, res) => {
  res.send('Hello, world!');
});
app.listen(3000, () => {
  console.log('Server started on port 3000');
});            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是错误的。下一个中间件并不总是意味着“路由器处理程序”。 Next() 函数重定向到另一个函数。
例如下面的例子,
// Middleware function 1 app.use((req, res, next) => { console.log("Middleware 1"); next(); // Move to the next middleware }); // Route handler app.get("/", (req, res, next) => { console.log("GET /"); next(); }); // Middleware function 2 app.use((req, res) => { console.log("Middleware 2"); res.send("Hello, world!"); });控制台输出:
浏览器中的响应为
Hello, world!。因此,next() 函数并不总是意味着路由器处理程序。