app.use(fn) 注册的函数,每个请求都会"> app.use(fn) 注册的函数,每个请求都会"> app.use(fn) 注册的函数,每个请求都会">
Node.js 词条目录
前端Wiki/Node.js/实战/从脚本到 Web 服务

Express 中间件机制

中间件(middleware)是 Express 的灵魂:一个 app.use(fn) 注册的函数,每个请求都会路过它。它按注册顺序依次执行,调用 next() 移交控制权——不调 next 请求就永远挂起。

中间件函数签名 (req, res, next),三岔路口:想继续就 next()、想拦截就 res.send() 终结、出错就 next(err) 跳到错误处理链。日志、鉴权、CORS、限流全都是中间件。

  • 顺序执行:use/路由按代码顺序匹配,next() 交给下一个
  • 不调 next() 就要自己 res.send() 终结,否则请求挂起
  • 错误中间件四参数 (err,req,res,next),放最后统一兜底
JS
const express = require('express');
const app = express();

// ① 日志中间件:每个请求都会路过
app.use((req, res, next) => {
  console.log(new Date().toISOString(), req.method, req.url);
  next();                                   // 移交控制权,否则请求挂起
});

// ② 鉴权中间件:只保护 /api 前缀
app.use('/api', (req, res, next) => {
  const token = req.headers['authorization'];
  if (!token) return res.status(401).json({ error: '未登录' });
  next();
});

app.get('/api/me', (req, res) => res.json({ name: '小明' }));
app.get('/public', (req, res) => res.send('无需登录'));

// ③ 错误处理中间件(四参数,放最后)
app.use((err, req, res, next) => {
  console.error('出错了:', err.stack);
  res.status(500).json({ error: '服务器开小差' });
});

app.listen(3000);
本节要点中间件 = 请求流水线:next() 往下传、res.send() 拦截、next(err) 交错误处理;顺序决定一切。