第一篇介紹了生成器目錄設計。xyzcoding:Koa2第一篇:詳解生成器?zhuanlan.zhihu.com
接下來學習Koa2的中間件。
Koa2本身只能算一個極簡的HTTP服務器,自身不內置中間件,但是提供中間件內核。中間件是Koa2的核心,因此需要熟練掌握。
中間件是什么?
你可以把一個HTTP請求理解為水流,而各種各樣的中間件類似各種管道,它會對水流進行處理。每個中間件在HTTP請求過程中會改寫請求,響應等數據。
也就是我們常說的洋蔥模型。
我們可以通過一個實例理解上述的過程:
const Koa = require('koa')
const app = new Koa()
// 日志中間件app.use(async (ctx, next) => {
console.log('middleware before await');
const start = new Date()
await next() // 函數控制權轉移 console.log('middleware after await');
const ms = new Date() - start
console.log(`${ctx.method}${ctx.url}-${ms}ms`)
})
app.use(async(ctx, next) => {
console.log('response');
ctx.body = "hello koa2"
})
module.exports = app
終端:
middleware before await
response
middleware after await
中間件寫法
通用函數中間件
// 日志中間件app.use((ctx, next) => {
console.log('middleware before await');
const start = new Date()
return next().then(() => {
console.log('middleware after await');
const ms = new Date() - start
console.log(`${ctx.method}${ctx.url}-${ms}ms`)
})
})
上述寫法不夠簡潔。
生成器函數中間件
const convert = require('koa-convert');
// 日志中間件app.use(function* log(next) {
console.log('middleware before await');
const start = new Date()
yield next
const ms = new Date() - start
console.log(`${this.method}${this.url}-${ms}ms`)
})
這里有個小細節,因為我們這里中間件沒有使用箭頭函數,因此其實這里的this就是我們平時說的上下文對象ctx。這也說明了使用async箭頭函數式中間件時候,為什么Koa2需要顯示提供ctx對象, 就是為了解決此處用this引用會有問題。
async函數中間件
app.use(async ctx => {
ctx.body = 'Hello World';
});
上下文對象
在Koa2中,ctx是一次完整的HTTP請求的上下文,會貫穿這個請求的生命周期。也就是說在整個請求階段都是共享的。
createContext(req, res) {
const context = Object.create(this.context);
// request、response是Koa2內置的對象 // 業務中我們一般通過ctx.request、ctx.response訪問 const request = context.request = Object.create(this.request);
const response = context.response = Object.create(this.response);
// 掛在app自身 context.app = request.app = response.app = this;
// 掛在node原生的內置對象 // req: http://nodejs.cn/api/http.html#http_class_http_incomingmessage // res: http://nodejs.cn/api/http.html#http_class_http_serverresponse context.req = request.req = response.req = req;
context.res = request.res = response.res = res;
request.ctx = response.ctx = context;
request.response = response;
response.request = request;
// 最初的URL context.originalUrl = request.originalUrl = req.url;
// 一個中間件生命周期內公共的存儲空間 context.state = {};
return context;
}
ctx.body
ctx.body主要是Koa2返回數據到客戶端的方法。
// context.js
/**
* Response delegation.
*/
delegate(proto, 'response')
.access('body')
可見ctx.body實際上是對在response.js的body進行賦值操作。
ctx.body的一些特性:可以直接返回一個文本
可以返回一個HTML文本
可以返回JSON
ctx.body = 'hello'
ctx.body = '
h2
'ctx.body = {
name: 'kobe'
}
get status() {
return this.res.statusCode;
},
/*** Set response status code.** @param {Number} code* @api public*/
set status(code) {
if (this.headerSent) return;
assert(Number.isInteger(code), 'status code must be a number');
assert(code >= 100 && code <= 999, `invalid status code:${code}`);
this._explicitStatus = true;
this.res.statusCode = code;
// 客戶端發送的 HTTP 版本,message.httpVersionMajor 是第一個整數, message.httpVersionMinor 是第二個整數。 // http://nodejs.cn/api/http.html#http_message_httpversion // 設置狀態消息 http://nodejs.cn/api/http.html#http_response_statusmessage if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code];
if (this.body && statuses.empty[code]) this.body = null;
},
/*** Set response body.** @param {String|Buffer|Object|Stream} val* @api public*/
set body(val) {
// this._body是真正的body屬性或者說代理屬性 const original = this._body;
this._body = val;
// no content if (null == val) {
// 204 "no content" if (!statuses.empty[this.status]) this.status = 204;
if (val === null) this._explicitNullBody = true;
this.remove('Content-Type');
this.remove('Content-Length');
this.remove('Transfer-Encoding');
return;
}
// 設置狀態碼 if (!this._explicitStatus) this.status = 200;
// 設置content-type const setType = !this.has('Content-Type');
// string if ('string' === typeof val) {
// text/html or text/plain if (setType) this.type = /^\s*
this.length = Buffer.byteLength(val);
return;
}
// buffer if (Buffer.isBuffer(val)) {
if (setType) this.type = 'bin';
this.length = val.length;
return;
}
// stream if (val instanceof Stream) {
onFinish(this.res, destroy.bind(null, val));
if (original != val) {
val.once('error', err => this.ctx.onerror(err));
// overwriting if (null != original) this.remove('Content-Length');
}
if (setType) this.type = 'bin';
return;
}
// json this.remove('Content-Length');
this.type = 'json';
},
ctx.body的工作原理就是根據其賦值的類型,來對Content-Type頭進行處理,最后根據Content-Type類型值通過res.end,把數據寫入到瀏覽器。
ctx.redirect
瀏覽器重定向一般是向前或者向后重定向。
redirect(url, alt) {
// location if ('back' === url) url = this.ctx.get('Referrer') || alt || '/';
this.set('Location', encodeUrl(url));
// status if (!statuses.redirect[this.status]) this.status = 302;
// html if (this.ctx.accepts('html')) {
url = escape(url);
this.type = 'text/html; charset=utf-8';
this.body = `Redirecting to ${url}.`;
return;
}
// text this.type = 'text/plain; charset=utf-8';
this.body = `Redirecting to${url}.`;
},