中间件的概念其实就是串行执行,切面编程。

例子

  1. const Koa = require("koa");
  2. // 创建服务
  3. const app = new Koa();
  4. app.use(async (ctx, next) => {
  5. console.log(1);
  6. await next();
  7. console.log(2);
  8. });
  9. app.use(async (ctx, next) => {
  10. console.log(3);
  11. await next();
  12. console.log(4);
  13. });
  14. app.use(async (ctx, next) => {
  15. console.log(5);
  16. await next();
  17. console.log(6);
  18. });
  19. // 监听服务
  20. app.listen(3000);

输出

  1. // 1
  2. // 3
  3. // 5
  4. // 6
  5. // 4
  6. // 2

why?

想要知道为什么这样,最重要的是要理解next。

首先ctx是请求上下文对象,这里不赘述。那么next是啥?其实这里next最简单的理解就是下一个中间件。koa2接受的中间件都是async函数,这也解释了为什么next()之前需要加await。所以上述实例中执行循序是这样的:

  1. 中间1 console.log(1);
  2. next(中间件2)console.log(3);
  3. next(中间件3)console.log(5);
  4. 中间件3 next 执行完毕,执行 console.log(6);
  5. 中间件2 next 执行完毕,执行 console.log(4);
  6. 中间件1 next 执行完毕,执行 console.log(2);

TODO

理解了koa2中间件的原理,可以尝试编写:

  1. koa-bodyparser用于将请求content-type===formdata的数据转为json
  2. koa-ctrloger控制器日志输出器中间件