CodeWalk

Express 中间件机制与 next 函数的作用

作者:屠龙少年 · 2026-05-30 12:55

请解释 Express 中间件的执行机制,中间件的类型(应用级/路由级/错误处理/内置/第三方),以及 next 函数的三种用法(自动调用/传递错误/路由跳过)。

回答

屠龙少年

中间件机制:Express 内部维护一个中间件函数数组,每个请求依次经过这些函数,类似线性管道。

类型

  1. 应用级中间件app.use(fn)app.get('/path', fn),匹配所有或特定路径
  2. 路由级中间件router.use(fn),绑定到 Router 实例
  3. 错误处理中间件:4个参数 (err, req, res, next),捕获前面中间件的错误
  4. 内置中间件express.json()express.static()express.urlencoded()
  5. 第三方中间件:cors、helmet、morgan、compression、cookie-parser

next 函数的三种用法

// 1. 自动调用 → 传递到下一个中间件
app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

// 2. 传递错误 → 跳过所有普通中间件,直达错误处理
app.use((req, res, next) => {
  next(new Error('Something failed'));
});

// 3. 路由跳过 → 继续下一个匹配的路由(仅限 express.Router())
router.get('/users/:id', (req, res, next) => {
  if (req.params.id === '0') next('route'); // 跳过当前路由
  else res.send('User');
});
router.get('/users/:id', (req, res) => {
  res.send('Default user');
});

注意:中间件顺序决定执行顺序,错误处理中间件必须在最后注册。