77 # koa 中间件的应用

调用 next() 表示执行下一个中间件

javascript 复制代码
const Koa = require("koa");

const app = new Koa();

app.use(async (ctx, next) => {
    console.log(1);
    next();
    console.log(2);
});

app.use(async (ctx, next) => {
    console.log(3);
    next();
    console.log(4);
});

app.use(async (ctx, next) => {
    console.log(5);
    next();
    console.log(6);
});

app.listen(3000);

洋葱模型:

输出:135642

添加异步等待

javascript 复制代码
const Koa = require("koa");

const app = new Koa();

const log = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("kaimo313");
            resolve();
        }, 3000);
    });
};

app.use(async (ctx, next) => {
    console.log(1);
    next();
    console.log(2);
});

app.use(async (ctx, next) => {
    console.log(3);
    await log();
    next();
    console.log(4);
});

app.use(async (ctx, next) => {
    console.log(5);
    next();
    console.log(6);
});

app.listen(3000);

输出:132 kaimo313 564

koa 中要求每个 next 方法前面都必须增加 await 否则不存在等待效果

javascript 复制代码
const Koa = require("koa");

const app = new Koa();

const log = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("kaimo313");
            resolve();
        }, 3000);
    });
};

app.use(async (ctx, next) => {
    console.log(1);
    next();
    console.log(2);
    ctx.body = "hello 1";
});

app.use(async (ctx, next) => {
    console.log(3);
    await log();
    ctx.body = "hello 2";
    next();
    console.log(4);
});

app.use(async (ctx, next) => {
    console.log(5);
    ctx.body = "hello 3";
    next();
    console.log(6);
});

app.listen(3000);

会取中间件第一个执行完的结果

koa 的中间件原理:会将所有的中间件组合成一个大的 promise,当这个 promise 执行完毕后,会采用当前的 ctx.body 进行结果的响应(next 前面必须要有 await 或者 return 否则执行顺序可能达不到预期)

如果都是同步执行,加不加 await 都无所谓,由于不知道后续是否有异步逻辑,写的时候都要加上 await

next():

  1. 可以把多个模块通过 next 方法来链接起来
  2. 可以决定是否向下执行(可以用来实现后台的权限)
  3. 可以封装一些方法,在中间件中,封装向下执行

实现中间件计时器

javascript 复制代码
const Koa = require("koa");

const app = new Koa();

const log = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("kaimo313");
            resolve();
        }, 3000);
    });
};

app.use(async (ctx, next) => {
    console.time("kaimo");
    await next();
    ctx.body = "hello 1";
    console.timeEnd("kaimo");
});

app.use(async (ctx, next) => {
    await log();
    ctx.body = "hello 2";
    return next();
});

app.use(async (ctx, next) => {
    ctx.body = "hello 3";
    return next();
});

app.listen(3000);
相关推荐
常常有21 小时前
中间件与依赖系统:构建高效 Web 后端的双重利器
开发语言·python·中间件·fastapi
无风听海1 天前
UseForwardedHeaders 与 UsePathBase:深入理解 ASP.NET Core 代理感知中间件
后端·中间件·asp.net
CSharp精选营1 天前
.NET 8 Web开发入门(三):解构引擎——依赖注入(DI)与中间件管道
中间件·asp.net core·依赖注入·ioc容器·请求管道·服务生命周期
fuquxiaoguang2 天前
CVE-2026-41690深度解析:一个HTTP请求如何击穿Node.js中间件防线
http·中间件·node.js·cve-2026-41690
冷小鱼2 天前
JVM 深度调优实战:从 JDK 8 到 JDK 21 的演进与中间件落地
java·jvm·中间件
STAT abil2 天前
docker离线安装及部署各类中间件(x86系统架构)
docker·中间件·系统架构
fuquxiaoguang2 天前
从监控面板到自主修复:AI智能体正在重新定义中间件运维
运维·人工智能·中间件·opsai
圣·杰克船长2 天前
kafka专题_大纲介绍
中间件·kafka
fuquxiaoguang3 天前
0.8W跑10B模型:端侧AI的“寒武纪爆发“与中间件的轻量进化
人工智能·中间件·端侧ai
van久3 天前
Day24:JWT 权限验证中间件 + 认证授权全套实战(笔记 + 面试题 + 落地步骤)
笔记·中间件