1.logger
koa一個重要設計就是中間件停撞,首先先看logger打印日志的功能县踢。
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`)
也可以拆分獨立函數(shù)
const logger=(ctx,next)=>{
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
中間件就是在request和response請求之間實現(xiàn)中間功能转绷。
app.use來加載中間件,其中中間件默認接收兩個參數(shù),第一個是context對象硼啤,第二個是next函數(shù)议经,調用next函數(shù),就可以把執(zhí)行權轉交給下一個中間件谴返。
2.中間件棧
多個中間件形成棧結構煞肾,先進后出。
1.最外層的中間件首先執(zhí)行嗓袱。
2.調用next函數(shù)把執(zhí)行權交給下一個中間件籍救。
3.最內層的中間件最后執(zhí)行
4.執(zhí)行結束執(zhí)行權交給上一層中間件
5.最外層中間件收回執(zhí)行權后,執(zhí)行next函數(shù)之后的代碼渠抹。
const one = (ctx, next) => {
console.log('>> one');
next();
console.log('<< one');
}
const two = (ctx, next) => {
console.log('>> two');
next();
console.log('<< two');
}
const three = (ctx, next) => {
console.log('>> three');
next();
console.log('<< three');
}
app.use(one);
app.use(two);
app.use(three);
輸出:
>> one
>> two
>> three
<< three
<< two
<< one
即先執(zhí)行最外層one钧忽,執(zhí)行到最內層,再執(zhí)行最能層代碼逼肯,最后最外層one收回執(zhí)行權耸黑。
如果把two的next注釋:
>> one
>> two
<< two
<< one
執(zhí)行到two沒有next因此不再執(zhí)行。
3.異步中間件
異步中間件必須攜程async函數(shù)形式篮幢。
const fs = require('fs.promised');
const Koa = require('koa');
const app = new Koa();
const main = async function (ctx, next) {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./demos/template.html', 'utf8');
};
app.use(main);
app.listen(3000);
中間件必須攜程async函數(shù)大刊,fs.readFile是異步操作必須攜程await