目录

koa2洋葱模型

# koa2洋葱模型

  • 中间件机制,是koa2的精髓
  • 每个中间件都是async函数
  • 中间件的运行机制,就像洋葱圈

# 洋葱圈模型和中间件模型的关系

  • 中间件机制:业务模块的划分
  • 洋葱圈模型:中间件的执行机制
  • 两者要分开来看,不要混在一起
// 演示 koa2 中间件的洋葱圈模型

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

// logger
app.use(async (ctx, next) => {
    await next() // 执行下一个中间件
    const rt = ctx.response.get('X-Response-Time') // 获取 时间差
    console.log(`${ctx.method} ${ctx.url} - ${rt}`)
})

// x-response-time
app.use(async (ctx, next) => {
    const start = Date.now()
    await next() // 执行下一个中间件
    const ms = Date.now() - start // 计算时间差,例如 80
    ctx.set('X-Response-Time', `${ms}ms`) // 记录/设置 时间差
})

// response
app.use(async (ctx, next) => {
    ctx.body = 'Hello world'
})

app.listen(3000)
console.log('koa2 已经开始监听 3000 端口')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
上次更新: 2022/05/12 14:57:53
最近更新
01
关于我
07-14
02
科学上网
11-15
03
OSS+CDN
09-23
更多文章>
极昼青春
买辣椒也用券