本文将以 **Node.js 中间件封装** 为主题,从 **原理 → 设计 → 封装模式 → 实战示例 → 工程化建议**
一、什么是 Node.js 中间件?
一句话理解
**中间件就是夹在“请求”和“响应”之间的一层可复用逻辑**
中间件解决什么问题?
二、中间件的设计核心思想
中间件的 4 个基本原则
-
-
-
-
三、Koa / Express 中间件模型对比
Express 中间件
Koa 中间件(洋葱模型)
async (ctx, next) => { await next();}
四、中间件封装的基本模板(Koa 示例)
标准中间件结构
function middleware(options) { return async function (ctx, next) { await next(); };}
为什么要用「工厂函数」?
五、实战一:日志中间件封装
需求
封装实现
function logger() { return async (ctx, next) => { const start = Date.now(); await next(); const cost = Date.now() - start; console.log( [</span><span class="code-snippet__string"><span class="code-snippet__subst">${ctx.method}</span></span><span class="code-snippet__string">] </span><span class="code-snippet__string"><span class="code-snippet__subst">${ctx.url}</span></span><span class="code-snippet__string"> - </span><span class="code-snippet__string"><span class="code-snippet__subst">${cost}</span></span><span class="code-snippet__string">ms ); };}
使用
六、实战二:统一错误处理中间件
为什么必须封装?
封装示例
function errorHandler() { return async (ctx, next) => { try { await next(); } catch (err) { ctx.status = err.status || 500; ctx.body = { code: ctx.status, message: err.message }; } };}
放置位置(非常重要)
七、实战三:鉴权中间件封装
封装目标
示例实现
function auth() { return async (ctx, next) => { const token = ctx.headers.authorization; if (!token) { ctx.throw(401, '未登录'); } ctx.state.user = verifyToken(token); await next(); };}
八、实战四:限流中间件(Redis)
典型「工程级中间件」
function rateLimit({ max, window }) { return async (ctx, next) => { const key = rate:</span><span class="code-snippet__string"><span class="code-snippet__subst">${ctx.ip}</span></span><span class="code-snippet__string">; const count = await redis.incr(key); if (count === 1) { await redis.expire(key, window); } if (count > max) { ctx.status = 429; ctx.body = '请求过于频繁'; return; } await next(); };}
九、中间件的组合与执行顺序
执行顺序示例
app.use(errorHandler());app.use(logger());app.use(auth());app.use(rateLimit());app.use(router.routes());
顺序设计原则
十、如何写「高质量中间件」?
Checklist
十一、中间件工程化目录结构建议
middlewares/ ├─ auth.js ├─ logger.js ├─ rateLimit.js ├─ errorHandler.js └─ index.js
module.exports = { auth, logger, rateLimit, errorHandler};
十二、常见反模式(一定要避免)
十三、总结
Node.js 中间件封装的本质是:把“横切关注点”从业务中剥离出来。
文章评论