拿以下這段代碼為例:
const Koa = require('koa');
const app = new Koa();
// x-response-time
app.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// logger
app.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);

每一個中間件就類似每一層洋蔥圈,上面例子中的第一個中間件 "x-response-time" 就好比洋蔥的最外層,第二個中間件 "logger" 就好比第二層,第三個中間件 "response" 就好比最里面那一層,所有的請求經過中間件的時候都會執行兩次。
