Koa
和 Express
都會使用到中間件
Express的中間件是順序執行,從第一個中間件執行到最后一個中間件,發出響應如上圖
Koa是從第一個中間件開始執行,遇到 next
進入下一個中間件,一直執行到最后一個中間件,在逆序,執行上一個中間件 next
之后的代碼,一直到第一個中間件執行結束才發出響應如上圖
見代碼
const Koa = require('koa2');
const app = new Koa();
const port = 9000;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)=>{console.log(5)
})app.listen(port, ()=>{console.log('Server is running at http://localhost:'+port);
})
那么在瀏覽器刷新后,控制臺得到的順序是:
?
?