Koa.js - 級聯



中介軟體函式是可以訪問上下文物件和應用程式請求-響應週期中下一個中介軟體函式的函式。這些函式用於修改請求和響應物件以執行解析請求體、新增響應頭等任務。Koa 更進一步,透過 yield “下游”,然後將控制流回“上游”。這種效果稱為級聯

以下是一箇中間件函式執行的簡單示例。

var koa = require('koa');
var app = koa();
var _ = router();

//Simple request time logger
app.use(function* (next) {
   console.log("A new request received at " + Date.now());
   
   //This function call is very important. It tells that more processing is 
   //required for the current request and is in the next middleware function/route handler.
   yield next;
});

app.listen(3000);

上述中介軟體會在伺服器上的每個請求時被呼叫。因此,每次請求後,我們都會在控制檯中看到以下訊息。

A new request received at 1467267512545

要將其限制在特定路由(及其所有子路由),我們只需像路由那樣建立路由即可。實際上,正是這些中介軟體處理了我們的請求。

例如:

var koa = require('koa');
var router = require('koa-router');
var app = koa();

var _ = router();

//Simple request time logger
_.get('/request/*', function* (next) {
   console.log("A new request received at " + Date.now());
   yield next;
});

app.use(_.routes());
app.listen(3000);

現在,每當您請求 '/request' 的任何子路由時,它才會記錄時間。

中介軟體呼叫順序

Koa 中介軟體最重要的方面之一是,它們在檔案中編寫/包含的順序就是它們下游執行的順序。一旦我們在中介軟體中遇到 yield 語句,它就會切換到下一個中介軟體,直到到達最後一個。然後我們再次開始向上移動,並從 yield 語句恢復函式。

例如,在以下程式碼片段中,第一個函式先執行到 yield,然後是第二個中介軟體到 yield,然後是第三個。由於這裡沒有更多中介軟體,我們開始向上移動,按相反的順序執行,即第三個、第二個、第一個。此示例總結了 Koa 使用中介軟體的方式。

var koa = require('koa');
var app = koa();

//Order of middlewares
app.use(first);
app.use(second);
app.use(third);

function *first(next) {
   console.log("I'll be logged first. ");
   
   //Now we yield to the next middleware
   yield next;
   
   //We'll come back here at the end after all other middlewares have ended
   console.log("I'll be logged last. ");
};

function *second(next) {
   console.log("I'll be logged second. ");
   yield next;
   console.log("I'll be logged fifth. ");
};

function *third(next) {
   console.log("I'll be logged third. ");
   yield next;
   console.log("I'll be logged fourth. ");
};

app.listen(3000);

執行此程式碼後訪問 '/' 時,我們的控制檯將顯示:

I'll be logged first. 
I'll be logged second. 
I'll be logged third. 
I'll be logged fourth. 
I'll be logged fifth. 
I'll be logged last. 

下圖總結了上述示例中實際發生的情況。

Middleware Desc

現在我們知道了如何建立自己的中介軟體,讓我們討論一些最常用的社群建立的中介軟體。

第三方中介軟體

express 的第三方中介軟體列表在此處可用。以下是一些最常用的中介軟體:

  • koa-bodyparser
  • koa-router
  • koa-static
  • koa-compress

我們將在後續章節中討論多箇中間件。

廣告
© . All rights reserved.