本章內容主要參考官網
- 簡介
- 應用
- Context(上下文)
- 請求(Request)
- 響應(Response)
簡介
koa 是由 Express 原班人馬打造的,致力于成為一個更小、更富有表現力、更健壯的 Web 框架。使用 koa 編寫 web 應用,通過組合不同的 generator,可以免除重復繁瑣的回調函數嵌套,并極大地提升錯誤處理的效率。koa 不在內核方法中綁定任何中間件,它僅僅提供了一個輕量優雅的函數庫,使得編寫 Web 應用變得得心應手。
安裝
Koa 目前需要 >=0.11.x版本的 node 環境。并需要在執行 node 的時候附帶 --harmony 來引入 generators 。
$ npm install -g n
$ n 0.11.12
$ node --harmony my-koa-app.js
應用
// koa.js
const koa = require('koa')
var app = new koa()
app
.use(function* () {
this.body = {
name: 'aaa'
}
})
.listen(3000, 'localhost', () => {
console.log('starting on port: ', 3000)
})
中間件級聯
下面的例子在頁面中返回 "Hello World",然而當請求開始時,請求先經過 x-response-time 和 logging 中間件,并記錄中間件執行起始時間。 然后將控制權交給 reponse 中間件。當中間件運行到 yield next 時,函數掛起并將控制前交給下一個中間件。當沒有中間件執行 yield next 時,程序棧會逆序喚起被掛起的中間件來執行接下來的代碼。
//koa1.js
var koa = require('koa');
var app = new koa();
// x-response-time
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
// logger
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
});
// response
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);
配置
應用配置是 app 實例屬性,目前支持的配置項如下:
app.name 應用名稱(可選項)
app.env 默認為 NODE_ENV 或者 development
app.proxy 如果為 true,則解析 "Host" 的 header 域,并支持 X-Forwarded-Host
app.subdomainOffset 默認為2,表示 .subdomains 所忽略的字符偏移量。
app.listen(...)
app.listen(...) 實際上是以下代碼的語法糖:
var http = require('http');
var koa = require('koa');
var app = new koa();
http.createServer(app.callback()).listen(3000);
這意味著您可以同時支持 HTTP 和 HTTPS,或者在多個端口監聽同一個應用。
var http = require('http');
var koa = require('koa');
var app = new koa();
http.createServer(app.callback()).listen(3000);
http.createServer(app.callback()).listen(3001);
//listen.js
const koa = require('koa')
var app = new koa()
app.use(function* () {
this.body = {
name: 'aaa'
}
})
app.listen(3000, 'localhost', () => {
console.log('starting on port: ', 3000)
})
app.listen(3001, 'localhost', () => {
console.log('starting on port: ', 3001)
})
app.use(function)
為應用添加指定的中間件,詳情請看 Middleware
Context(上下文)
Koa Context 將 node 的 request 和 response 對象封裝在一個單獨的對象里面,其為編寫 web 應用和 API 提供了很多有用的方法。
這些操作在 HTTP 服務器開發中經常使用,因此其被添加在上下文這一層,而不是更高層框架中,因此將迫使中間件需要重新實現這些常用方法。
context 在每個 request 請求中被創建,在中間件中作為接收器(receiver)來引用,或者通過 this 標識符來引用:
app.use(function *(){
this; // is the Context
this.request; // is a koa Request
this.response; // is a koa Response
});
Koa 不支持 直接調用底層 res 進行響應處理。請避免使用以下 node 屬性:
res.statusCode
res.writeHead()
res.write()
res.end()
app.keys=
設置簽名Cookie密鑰,該密鑰會被傳遞給 KeyGrip。
app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256')
ctx.throw(msg, [status])
拋出包含 .status 屬性的錯誤,默認為 500。該方法可以讓 Koa 準確的響應處理狀態。 Koa支持以下組合:
this.throw(403)
this.throw('name required', 400)
this.throw(400, 'name required')
this.throw('something exploded')
請求(Request)
Koa Request 對象是對 node 的 request 進一步抽象和封裝,提供了日常 HTTP 服務器開發中一些有用的功能。
響應(Response)
Koa Response 對象是對 node 的 response 進一步抽象和封裝,提供了日常 HTTP 服務器開發中一些有用的功能。