中间件是什么
中间件函数是一个带有ctx和next两个参数的简单函数。ctx是上一篇降到的上下文,封装了Request和Response等对象;next用于把中间件的执行权交给下游的中间件。
中间件执行顺序
中间件执行顺序按照洋葱模型,通过await next()将执行权一层一层交给下层,执行到底部时,又一层一层往上执行await next()函数后的内容。
代码示例:
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
let stime = new Date().getTime();
await next();
let etime = new Date().getTime();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello world</h1>';
console.log(`请求地址:${ctx.path}, 响应时间:${etime - stime}ms`);
})
app.use(async (ctx, next) => {
console.log('中间件 doSomething');
await next();
console.log('中间件执行over');
})
app.listen(3000, () => {
console.log('server is listening at http://localhost:3000');
})