1、koa2背景
Express簡介:
koa是Express的下一代基於Node.js的web框架,目前有1.x和2.0兩個版本. 雖然Express的API很簡單,但是它是基於ES5的語法,要實現異步代碼,只有一個方法:回調。
如果異步嵌套層次過多,代碼寫起來就非常難看, 雖然可以用async這樣的庫來組織異步代碼,但是用回調寫異步實在是太痛苦了!
koa 1.0簡介:
隨着新版Node.js開始支持ES6,Express的團隊又基於ES6的generator重新編寫了下一代web框架koa。和Express相比,koa 1.0使用generator實現異步。
var koa = require('koa'); var app = koa(); app.use('/test', function *() { yield doReadFile1(); var data = yield doReadFile2(); this.body = data; });
app.listen(3000);
用generator實現異步比回調簡單了不少,但是generator的本意並不是異步。Promise才是為異步設計的,但是Promise的寫法……想想就復雜。因此2.0應運而生。
koa 2.0簡介:
koa團隊並沒有止步於koa 1.0,他們非常超前地基於ES7開發了koa2,和koa 1相比,koa2完全使用Promise並配合async來實現異步。
app.use(async (ctx, next) => { await next(); //ctx -- context上下文:ctx是Koa傳入的封裝了request和response的變量 ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, Koa2!</h1>' });
什么感覺?是不是很爽?異步-同步的感覺
2、koa2入門
步驟一:新建文件夾 learnKoa
步驟二:新建 app.js
'use strict'; const Koa = require('koa'); const app = new Koa(); app.use(async (ctx, next) => { await next(); //ctx -- context上下文:ctx是Koa傳入的封裝了request和response的變量 ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, Koa2!</h1>' }) app.listen(3000) console.log('app started at port 3000...')
步驟三:新建 package.json
{ "name": "learn-koa2", "version": "1.0.0", "description": "learn Koa 2", "main": "app.js", "scripts": { "start": "node app.js" }, "keywords": [ "koa", "async" ], "author": "david pan", "dependencies": { "koa": "2.0.0" } }
步驟四:npm install
步驟五:npm run start, 瀏覽器打開http://localhost:3000/,恭喜你,踏上新的征途!
3、koa middleware
async函數稱為middleware
'use strict'; const Koa = require('koa'); const app = new Koa(); app.use(async (ctx, next) => { console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL await next(); // 調用下一個middleware }); app.use(async (ctx, next) => { const start = new Date().getTime(); // 當前時間 await next(); // 調用下一個middleware const ms = new Date().getTime() - start; // 耗費時間 console.log(`Time: ${ms}ms`); // 打印耗費時間 }); app.use(async (ctx, next) => { await next(); //ctx -- context上下文:ctx是Koa傳入的封裝了request和response的變量 ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, Koa2!</h1>' }); app.listen(3000); console.log('app started at port 3000...');
注意點:
a. koa把很多async函數組成一個處理鏈,每個async函數都可以做一些自己的事情,然后用await next()來調用下一個async函數。
b. middleware的順序很重要,也就是調用app.use()的順序決定了middleware的順序。
c. 如果一個middleware沒有調用await next(), 后續的middleware將不再執行。
例如:一個檢測用戶權限的middleware可以決定是否繼續處理請求,還是直接返回403錯誤
app.use(async (ctx, next) => { if (await checkUserPermission(ctx)) { await next(); } else { ctx.response.status = 403; } });
————————————————
版權聲明:本文為CSDN博主「空谷足音 -จุ」的原創文章