文章不易,请关注公众号 毛毛虫的小小蜡笔,多多反对,谢谢
先看个Demo
app.use(async (ctx, next) => {
console.log(1)
await next()
console.log(2)
ctx.body = 'Hello Koa';
});
app.use(async (ctx, next) => {
console.log(3)
await next()
console.log(4)
});
app.use(async (ctx, next) => {
console.log(5)
});
输入后果是:
1
3
5
4
2
这就是所谓的洋葱模型。
第一个中间件在最外层,而后第二个在第二层,第三个则是最外面一层。
所以先执行1,而后到第二层的3,再到最外面的5,执行完后再到第二层的4,最初返回到第一层的2。
看源码
app.use最次要的是把中间件存起来:this.middleware.push(fn)。
详情 请查看:毛毛虫的小小蜡笔
发表回复