目录

Koa.js - 级联( Cascading)

中间件函数是可以在应用程序的请求 - 响应周期中访问context object和下一个中间件函数的函数。 这些函数用于修改任务的请求和响应对象,例如解析请求主体,添加响应头等。Koa更进一步,产生'downstream' ,然后将控制回流'upstream' 。 此效果称为cascading

以下是一个中间件功能的简单示例。

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. 

下图总结了上例中实际发生的情况。

中间件描述

现在我们知道如何创建自己的中间件,让我们讨论一些最常用的社区创建的中间件。

第三方中间件

here.提供了Express的第三方中间件列表here. 以下是一些最常用的中间件 -

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

我们将在后续章节中讨论多个中间件。

↑回到顶部↑
WIKI教程 @2018