當(dāng)一個(gè)中間件調(diào)用 next() 則該函數(shù)暫停并將控制傳遞給定義的下一個(gè)中間件。當(dāng)在下游沒(méi)有更多的中間件執(zhí)行后,堆棧將展開(kāi)并且每個(gè)中間件恢復(fù)執(zhí)行其上游行為。
// require("babel-register");
const http = require('http');
const https = require('https');
const Koa = require('koa');
const nexttest = require("./nexttest");
const app = new Koa();
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
console.log('------1---------');
await next();
console.log('------2---------');
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// logger
app.use(async (ctx, next) => {
const start = Date.now();
console.log('------3--------');
await next();
console.log('------4---------');
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
app.use(async (ctx, next) => {
console.log('------5--------');
await next();
console.log('------6---------');
});
// response
app.use(async ctx => {
console.log('------7---------');
ctx.body = ctx.response.status;
});
http.createServer(app.callback()).listen(3000);
// https.createServer(app.callback()).listen(3000);
輸出:
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET / - 2
------2---------
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET / - 0
------2---------
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET /favicon.ico - 0
------2---------