中间件的概念其实就是串行执行,切面编程。
例子
const Koa = require("koa");
// 创建服务
const app = new Koa();
app.use(async (ctx, next) => {
console.log(1);
await next();
console.log(2);
});
app.use(async (ctx, next) => {
console.log(3);
await next();
console.log(4);
});
app.use(async (ctx, next) => {
console.log(5);
await next();
console.log(6);
});
// 监听服务
app.listen(3000);
输出
// 1
// 3
// 5
// 6
// 4
// 2
why?
想要知道为什么这样,最重要的是要理解next。
首先ctx是请求上下文对象,这里不赘述。那么next是啥?其实这里next最简单的理解就是下一个中间件。koa2接受的中间件都是async函数,这也解释了为什么next()之前需要加await。所以上述实例中执行循序是这样的:
- 中间1 console.log(1);
- next(中间件2)console.log(3);
- next(中间件3)console.log(5);
- 中间件3 next 执行完毕,执行 console.log(6);
- 中间件2 next 执行完毕,执行 console.log(4);
- 中间件1 next 执行完毕,执行 console.log(2);
TODO
理解了koa2中间件的原理,可以尝试编写:
- koa-bodyparser用于将请求content-type===formdata的数据转为json
- koa-ctrloger控制器日志输出器中间件