KOA技术分享

专注 Koa.js 框架的编程知识分享

深入理解 Koa 洋葱模型与中间件机制

洋葱模型解析

Koa 的中间件执行顺序像洋葱一样,从外层到内层,再从内层回到外层。每个中间件都可以通过 await next() 控制流程。

中间件的基本结构

const middleware = async (ctx, next) => {
  // 请求阶段
  console.log('请求处理前');

  await next(); // 交给下一个中间件

  // 响应阶段
  console.log('响应处理后');
};

实用中间件示例

日志中间件

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

响应时间中间件

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  ctx.set('X-Response-Time', `${Date.now() - start}ms`);
});

中间件组合

可以使用 koa-compose 手动组合中间件:

const compose = require('koa-compose');

const middlewares = [logger, auth, router];
app.use(compose(middlewares));

错误处理中间件

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = { error: err.message };
    ctx.app.emit('error', err, ctx);
  }
});
← 上一篇:Koa.js 入门指南 下一篇:使用 koa-router 构建 RESTful API →