Koa2 和 Express 中间件对比

koa2 中间件 koa2的中间件是通过 async await 实现的,中间件执行顺序是“洋葱圈”模型。 中间件之间通过next函数联系,当一个中间件调用 next() 后,会将控制权交给下一个中间件, 直到下一个中间件不再执行 next() 后, 将会沿路折返,将控制权依次交换给前一个中间件。 如图: koa2 中间件实例 app.js: `const Koa = require('koa'); const app = new Koa(); // logger app.use(async (ctx, next) => { console.log('第一层 - 开始') await next(); const rt = ctx.response.get('X-Response-Time'); console.log(`<span class="katex math inline">{ctx.method} -----------</span>{ctx.url} ----------- <span class="katex math inline">{rt}`); console.log('第一层 - 结束') }); // x-response-time app.use(async (ctx, next) => { console.log('第二层 - 开始') const start = Date.now(); await next(); const ms = Date.now() - start; ctx.set('X-Response-Time', `</span>{ms}ms`); console.log('第二层 - 结束') }); // response app.use(async ctx => { console.log('第三层 - 开始') ctx.body = 'Hello World'; console.log('第三层 - 结束') }); app.listen(3000); ` 执行app.js后,浏览器访问 http://localhost:3000/text , 控制台输出结果: ...

2020年3月26日 · 3 分钟 · 天边的星星