← 返回目录

第 5 卷

第 5 / 12 卷日期:

const Koa = require('koa');

const app = new Koa();

// 中间件1:异步中间件 app.use(async (ctx, next) => {

console.log("中间件1 开始");

await next(); // 等待下一个中间件执行完成 console.log("中间件1 结束");

});

// 中间件2 app.use(async (ctx, next) => {

console.log("中间件2 开始");

ctx.body = "Hello Koa"; // 设置响应体 await next();

console.log("中间件2 结束");

});

// 中间件3 app.use(async (ctx, next) => {

console.log("中间件3 开始");

await next();

console.log("中间件3 结束");

});

// 输出顺序:中间件1 开始 > 中间件2 开始 > 中间件3 开始 > 中间件3 结束 > 中间件 2 结束 > 中间件1 结束

app.listen(3000);

示例:

const Router = require('koa-router');

const router = new Router({ prefix: '/api' }); // 路由前缀

// 路由级中间件:仅作用于当前路由 router.use(async (ctx, next) => {

console.log("路由级中间件处理");

if (!ctx.query.token) { ctx.status = 401;

ctx.body = "缺少token";

return;

} await next();

});

router.get('/user', async (ctx) => { ctx.body = { id: 1, name: "张三" };

});

app.use(router.routes()).use(router.allowedMethods()); // 注册路由及允许的HTTP方法

示例:

// 全局错误处理中间件(需放在所有中间件最前面)

app.use(async (ctx, next) => { try {

await next(); // 执行后续中间件 // 处理404

if (ctx.status === 404) { ctx.status = 404;

ctx.body = "页面不存在";

} } catch (err) {

console.error("错误信息:", err.stack);

ctx.status = err.status || 500;

ctx.body = err.message || "服务器内部错误";

} });

// 触发错误 app.use(async (ctx, next) => {

throw new Error("自定义错误");

});

八、Express、Koa的源码是如何实现和工作的?

  1. Express源码实现核心

Express源码(核心文件: lib/express.js、 lib/application.js、 lib/router/index.js)核心是“中间件链表+路由匹配”,工作流程如下:

  1. 核心类:Application

Express的入口是 express() 函数,该函数返回 Application 类的实例( app)。

  • Application 类继承自 events.EventEmitter,支持事件监听(如 error 事件);
  • 核心属性: _router(Router实例,管理路由和中间件)、 settings(应用配置)、

middleware(应用级中间件数组);

  • 核心方法: use()(注册中间件,最终调用 _router.use())、 get() / post() 等

HTTP方法(注册路由,调用 _router.METHOD())、 listen()(启动HTTP服务器,调用

全站分卷索引 · 12 卷
  1. 1第 1 卷
  2. 2第 2 卷
  3. 3第 3 卷
  4. 4第 4 卷
  5. 5第 5 卷
  6. 6第 6 卷
  7. 7第 7 卷
  8. 8第 8 卷
  9. 9第 9 卷
  10. 10第 10 卷
  11. 11第 11 卷
  12. 12第 12 卷