koa2中介軟體原理

2021-10-06 04:29:00 字數 1574 閱讀 3319

koa2中介軟體的執行就像洋蔥圈一樣,從外面到最裡面,再從最裡面到最外面。

const koa = require('koa');

// logger

console.log('第一層洋蔥圈開始')

await next();

const rt = ctx.response.get('x-response-time');

console.log('第一層洋蔥圈結束')

console.log(`$ $ - $`);

});// x-response-time

console.log('第二層洋蔥圈開始')

const start = date.now();

await next();

const ms = date.now() - start;

ctx.set('x-response-time', `$ms`);

console.log('第二層洋蔥圈結束')

});// response

console.log('第三層洋蔥圈開始')

ctx.body = 'hello world';

console.log('第三層洋蔥圈結束')

});

執行上述**的結果是:

第一層洋蔥圈開始

第二層洋蔥圈開始

第三層洋蔥圈開始

第三層洋蔥圈結束

第二層洋蔥圈結束

第一層洋蔥圈結束

like-koa2.js檔案中

//組合中介軟體

function compose(middlewarelist)catch(err)

}return dispatch(0) //返回執行dispath函式,傳參為0

}}class likeko2

use(fn)

createcontext(req,res)

ctx.query = req.query

return ctx

}handlerequest(ctx,fn)

callback()

}listen(...args)

}module.exports = likeko2test.js檔案中

const koa = require('./like-koa2');

// logger

await next();

const rt = ctx['x-response-time'];

console.log(`$ $ - $`);

});// x-response-time

const start = date.now();

await next();

const ms = date.now() - start;

ctx['x-response-time'] = `$ms`;

});// response

ctx.res.end('this is like koa2');

});

koa2 mysql 中介軟體 Koa2 中介軟體

1.什麼是koa2中介軟體?二 常用的五個中介軟體 1.koa 面向node.js的表示式http中介軟體框架,使web應用程式和api更加令人愉快地編寫。koa的中介軟體堆疊以類似堆疊的方式流動,允許您執行下游操作,然後過濾和處理上游的響應。ctx.body hello world 2.koa r...

koa2中介軟體簡易分析

koa generator支援koa1.x與koa2.x node 7.6 babel 安裝完成腳手架後,選擇不同的命令koa koa2。全域性安裝 npm install g koa generator快速建立專案結構,直接使用koa2命令即可,簡單粗暴 各可選引數的含義在koa generato...

koa2中介軟體實現原始碼解析

眾所周知,koa2核心的部分就是middleware和context了,本文將從結合官網demo以及原始碼對其進行解讀 const koa require koa x response time const start date.now await next const ms date.now st...