Express 的核心思想是「管道处理」:一个请求到来,依次经过一串中间件——日志、鉴权、解析 body、业务路由……每个中间件是 (req, res, next) => { ...; next() } 的函数,调 next() 把控制权交给下一个,也可以 res.send() 直接终结。这就是「洋葱模型」:请求从外向内穿过中间件链。
中间件分四类:应用级(app.use 挂全局)、路由级(挂在某路由)、错误处理(四个参数 (err, req, res, next))、内置(express.static / express.json)。经典易错:忘记调 next() 请求永远挂起;错误中间件一定要放在最后且必须有四个参数,否则被当成普通中间件。
const express = require('express'); const app = express(); // ① 应用级中间件:全局日志 app.use((req, res, next) => { console.log(req.method, req.url); next(); // ★ 不调 next 请求就挂这 }); // ② 内置中间件:解析 JSON body app.use(express.json()); // ③ 路由级中间件:鉴权 function auth(req, res, next) { if (req.headers.token === 'x') next(); else res.status(401).send('未登录'); } app.get('/profile', auth, (req, res) => { // 只挂这条路由 res.json({ name: 'Tom' }); }); // ④ 错误处理:四参数,放最后 app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('服务器错误'); }); app.listen(3000);