Skip to content
📈0️⃣

Koa 洋葱模型

Koa 的中间件机制被称为“洋葱模型”(Onion Model),因为中间件的执行顺序类似于剥洋葱一样,从外到内、再从内到外。这种模型可以让开发者更加灵活地控制请求的处理流程。

image-yangcong

在 Koa 中,每个中间件可以通过 next 参数来调用下一个中间件,而中间件的执行顺序由代码中的调用顺序决定。当一个请求进入 Koa 应用的时候,中间件会根据调用顺序依次执行,然后再返回响应。同时,在返回的过程中,中间件也会以相反的顺序执行。

image-yangcong

下面是一个简单的示例代码,演示了 Koa 中的洋葱模型:

javascript
const Koa = require("koa");
const app = new Koa();

// 第一个中间件
app.use(async (ctx, next) => {
  console.log("Middleware 1: In");
  await next();
  console.log("Middleware 1: Out");
});

// 第二个中间件
app.use(async (ctx, next) => {
  console.log("Middleware 2: In");
  await next();
  console.log("Middleware 2: Out");
});

// 第三个中间件
app.use(async (ctx, next) => {
  console.log("Middleware 3: In");
  await next();
  console.log("Middleware 3: Out");

  // 响应
  ctx.body = "Hello, Koa Onion Model";
});

// 启动服务器
app.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});

在上述示例中,我们定义了三个中间件,并按照调用顺序注册到 Koa 应用中。当请求发送到服务器时,中间件将按照顺序执行,控制台将输出以下内容:

Middleware 1: In
Middleware 2: In
Middleware 3: In
Middleware 3: Out
Middleware 2: Out
Middleware 1: Out

如上所示,中间件的执行顺序就像一个洋葱,由外而内再由内而外依次执行。最后,通过第三个中间件进行响应处理。