技术 · 思考 · 实践 · 成长

首页/Node/正文

Koa 框架与洋葱模型:中间件机制与 async 控制

Node5 次阅读

Koa 是 Express 原班人马的下一代框架:async 中间件 + 洋葱模型。本文讲清机制,结尾附计时中间件小案例。

一、Koa vs Express

对比ExpressKoa
中间件回调 next()async/await + 洋葱模型
错误处理4 参数中间件try/catch + ctx.throw
体积自带路由/静态极简(自己加)
上下文req/res 分离ctx 统一封装
适用快速开发精细控制中间件流

二、第一个 Koa 应用

npm install koa
const Koa = require('koa');
const app = new Koa();

app.use(async (ctx) => {
    ctx.body = 'Hello Koa';
});

app.listen(3000);

三、洋葱模型(重点)

app.use(async (ctx, next) => {
    console.log('A 进入');
    await next();                 // 进入下一层
    console.log('A 离开');        // 下层执行完回来
});
app.use(async (ctx, next) => {
    console.log('B 进入');
    await next();
    console.log('B 离开');
});
// 请求到达:A进入 → B进入 → B离开 → A离开(像穿洋葱)

特性:前处理 → 后处理天然成对 —— 计时、日志、鉴权的理想结构。

四、ctx 上下文

ctx.request.query      // GET 参数
ctx.request.body       // 需 koa-bodyparser
ctx.params.id          // 路由参数(koa-router)
ctx.set('X-Custom', '1');   // 响应头
ctx.status = 200;
ctx.body = { ok: true };   // 自动 JSON
ctx.throw(404, '不存在');   // 抛错误

五、错误处理

app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        ctx.status = err.status || 500;
        ctx.body = { message: err.message };
        ctx.app.emit('error', err, ctx);      // 记日志
    }
});
app.on('error', (err, ctx) => console.error(err.stack));

六、路由整合(koa-router)

const Router = require('koa-router');
const router = new Router({ prefix: '/api' });
router.get('/users', async (ctx) => { ctx.body = users; });
app.use(router.routes()).use(router.allowedMethods());

七、小案例:请求计时中间件

const Koa = require('koa');
const app = new Koa();

// 计时中间件(洋葱模型前后包夹)
app.use(async (ctx, next) => {
    const start = Date.now();
    await next();                              // 等所有下游执行完
    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
    console.log(`${ctx.method} ${ctx.url} ${ms}ms`);
});

// 简易鉴权(洋葱再包一层)
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/api') && ctx.headers.token !== 'secret') {
        ctx.throw(401, '未认证');
    }
    await next();
});

// 业务
app.use(async (ctx) => {
    await new Promise(r => setTimeout(r, 50));      // 模拟耗时
    ctx.body = { ok: true };
});

app.listen(3000);

计时(前后夹)+ 鉴权(前置拦截)—— 洋葱模型两层中间件的经典示范(curl 看响应头 X-Response-Time)。

八、总结

Koa 用 async 中间件;洋葱模型 = 进入/离开成对;ctx 统一上下文、ctx.throw 抛错;try/catch 最外层兜底;路由用 koa-router 挂载。

知识是抵御一切灾祸的盾牌

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读