当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并且每个中间件恢复执行其上游行为。
// 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---------