koa2的中间件(洋葱圈模型);app.get、app.post 和 app.use 的不同

app.use(...)都是中间件

app.get 和 app.post 路由也是中间件(只不过限制了url规则)

app.use 所有的网络请求都会经过这个。路由只是满足条件的才会走。如满足get或post方法。满足路由请求的路径。

image

一个请求要经过所有的中间件,一层层的洋葱和ABC都是中间件,中间件都是async await异步函数结构

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

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

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

image

image

posted @ 2021-03-25 17:39  嘿!那个姑娘  阅读(127)  评论(0编辑  收藏  举报