中间件是在 Express 的请求-响应周期中按顺序运行的函数。每个中间件接收 (req, res, next),可以检查/修改请求和响应,结束响应,或调用 next() 将控制权传递给下一个中间件。它们是 Express 应用如何构建的核心。
签名和链
js
app.( {
.();
();
});
关键规则:调用 next() 以继续链。如果忘记调用它(且不发送响应),请求将永远挂起。
Request → [logger] → [auth] → [body parser] → [route handler] → Response
next() next() next() res.send()
Each middleware runs in order; any can short-circuit by sending a response.
// 1. Application-level — runs for all (or path-matched) requests
app.use(express.json()); // built-in: parse JSON bodies
app.use(cors()); // third-party
// 2. Custom — e.g. authentication that can SHORT-CIRCUIT
function requireAuth(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).json({ error: "Unauthorized" }); // STOP — don't call next()
}
req.user = decodeToken(req.headers.authorization); // attach data for later handlers
next(); // authorized → continue
}
// 3. Route-specific
app.get("/profile", requireAuth, (req, res) => res.json(req.user));
中间件可以短路(发送响应且不调用 next(),例如阻止未授权的请求)或增强请求(为下游处理程序附加 req.user)。
// special signature with 4 params → Express treats it as an error handler
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Server error" });
});
// triggered by next(err) or a thrown error; place it LAST
错误处理程序有四个参数(err 在首位)。通过调用 next(err) 可以到达它;它应该最后注册。
Middleware runs in the ORDER you register it. Body parser before routes that
read the body; auth before protected routes; error handler last.
中间件是 Express(以及类似框架)的架构骨干——身份验证、日志记录、body 解析、CORS、验证和错误处理都是中间件。
理解 (req, res, next) 约定(特别是你必须调用 next() 或发送响应),中间件如何能够短路或增强请求,四参数错误处理程序,以及顺序很重要,对于构建、组织和调试任何 Express 应用都是必不可少的。