本系列文章是本人學習相關知識時所積累的筆記,以記錄自己的學習歷程,也爲了方便回顧知識;故文章內容較爲隨意簡練,抱着學習目的來的同學務必轉移他處,以免我誤人子弟~
koa的使用
創建後端服務器
原生的http
模塊提供的方法:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world');
});
server.listen(3000, () => {
console.log('server start at 3000');
});
在回調函數中,使用req和res對請求數據和響應數據進行處理
Koa創建服務:
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
let start = new Date().getTime();
await next();
let time = new Date().getTime() - start;
ctx.set("X-Response-Time", `${time}ms`);
});
app.use(async (ctx, next) => {
ctx.status = 200;
ctx.body = 'Hello World';
await next();
});
app.listen(3000);
Koa使用use方法接收中間件
ctx是對原生req和res的封裝,而next是中間件的關鍵,調用next實際上是跳出當前中間件進入下一個中間件
所謂中間件即是同步或異步函數
koa中間件的原理
- Koa將中間件按順序存放在數組中
- 每當中間件執行到next時,會進入下一個中間件,即內部實現將下一個中間件傳遞給next