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

// logger

app.use(async (ctx, next) => {
    console.log(1)
  await next();
  console.log(2)
  const rt = ctx.response.get('X-Response-Time');
  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

// x-response-time

app.use(async (ctx, next) => {
    console.log(3)
  const start = Date.now();
  await next();
  console.log(4)
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// response

app.use(async ctx => {
    console.log(5)
  ctx.body = 'Hello World111';
  console.log(6)
});

app.listen(3000);

以 “Hello World” 的响应作为示例,当请求开始时首先请求流通过 x-response-time 和 logging 中间件,然后继续移交控制给 response 中间件。当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并且每个中间件恢复执行其上游行为,这样就形成了洋葱形式的执行过程

上边的执行结果打印出来的结果就是

1
3
5
6
4
2
GET / - 4ms

 

相关文章:

  • 2021-07-22
  • 2022-12-23
  • 2021-10-03
  • 2021-07-18
  • 2021-11-11
  • 2021-11-27
  • 2022-01-15
猜你喜欢
  • 2022-12-23
  • 2021-04-09
  • 2021-06-13
  • 2022-12-23
  • 2019-06-03
  • 2022-12-23
  • 2021-07-10
相关资源
相似解决方案