koa-基于node.js平台的下一代web开发框架入门

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了koa-基于node.js平台的下一代web开发框架入门相关的知识,希望对你有一定的参考价值。

参考技术A koa 是由 Express 原班人马打造的,致力于成为一个更小、更富有表现力、更健壮的 Web 框架。使用 koa 编写 web 应用,通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套,并极大地提升错误处理的效率。koa 不在内核方法中绑定任何中间件,它仅仅提供了一个轻量优雅的函数库,使得编写 Web 应用变得得心应手。

Koa需要 node v7.6.0或更高版本来支持ES2015、异步方法

你可以安装自己支持的node版本。

在node < 7.6的版本中使用async 函数, 我们推荐使用babel's require hook.

为了解析和转译异步函数,你应该至少有transform-async-to-generator or transform-async-to-module-method这2个插件。例如,在你的.babelrc文件中,应该有如下代码

也可以使用env preset并设置"node": "current"来替代.

Koa 应用是一个包含一系列中间件 generator 函数的对象。 这些中间件函数基于 request 请求以一个类似于栈的结构组成并依次执行。 Koa 类似于其他中间件系统(比如 Ruby's Rack 、Connect 等), 然而 Koa 的核心设计思路是为中间件层提供高级语法糖封装,以增强其互用性和健壮性,并使得编写中间件变得相当有趣。

Koa 包含了像 content-negotiation(内容协商)、cache freshness(缓存刷新)、proxy support(代理支持)和 redirection(重定向)等常用任务方法。 与提供庞大的函数支持不同,Koa只包含很小的一部分,因为Koa并不绑定任何中间件。

任何教程都是从 hello world 开始的,Koa也不例外^_^:

Koa 的中间件通过一种更加传统(您也许会很熟悉)的方式进行级联,摒弃了以往 node 频繁的回调函数造成的复杂代码逻辑。 然而,使用异步函数,我们可以实现"真正" 的中间件。与之不同,当执行到 yield next 语句时,Koa 暂停了该中间件,继续执行下一个符合请求的中间件('downstrem'),然后控制权再逐级返回给上层中间件('upstream')。

下面的例子在页面中返回 "Hello World",然而当请求开始时,请求先经过 x-response-time 和 logging 中间件,并记录中间件执行起始时间。 然后将控制权交给 reponse 中间件。当一个中间件调用next()函数时,函数挂起并控件传递给定义的下一个中间件。在没有更多的中间件执行下游之后,堆栈将退出,并且每个中间件被恢复以执行其上游行为。

应用配置是 app 实例属性,目前支持的配置项如下:

Koa 应用并非是一个 1-to-1 表征关系的 HTTP 服务器。 一个或多个Koa应用可以被挂载到一起组成一个包含单一 HTTP 服务器的大型应用群。

如下为一个绑定3000端口的简单 Koa 应用,其创建并返回了一个 HTTP 服务器,为 Server#listen() 传递指定参数(参数的详细文档请查看nodejs.org)。

The app.listen(...) 实际上是以下代码的语法糖:

这意味着您可以同时支持 HTTPS 和 HTTPS,或者在多个端口监听同一个应用。

返回一个适合 http.createServer() 方法的回调函数用来处理请求。 您也可以使用这个回调函数将您的app挂载在 Connect/Express 应用上。

为应用添加指定的中间件,详情请看 Middleware

设置签名cookie密钥。

该密钥会被传递给KeyGrip, 当然,您也可以自己生成 KeyGrip. 例如:

在进行cookie签名时,只有设置 signed 为 true 的时候,才会使用密钥进行加密:

app.context是从中创建ctx的原型。 可以通过编辑app.context向ctx添加其他属性。当需要将ctx添加到整个应用程序中使用的属性或方法时,这将会非常有用。这可能会更加有效(不需要中间件)和/或更简单(更少的require()),而不必担心更多的依赖于ctx,这可以被看作是一种反向模式。

例如,从ctx中添加对数据库的引用:

注:

默认情况下Koa会将所有错误信息输出到 stderr, 除非 app.silent 是 true.当err.status是404或者err.expose时,默认错误处理程序也不会输出错误。要执行自定义错误处理逻辑,如集中式日志记录,您可以添加一个"错误"事件侦听器:

如果错误发生在 请求/响应 环节,并且其不能够响应客户端时,Contenxt 实例也会被传递到 error 事件监听器的回调函数里。

当发生错误但仍能够响应客户端时(比如没有数据写到socket中),Koa会返回一个500错误(Internal Server Error)。 无论哪种情况,Koa都会生成一个应用级别的错误信息,以便实现日志记录等目的。

Koa Context 将 node 的 request 和 response 对象封装在一个单独的对象里面,其为编写 web 应用和 API 提供了很多有用的方法。 这些操作在 HTTP 服务器开发中经常使用,因此其被添加在上下文这一层,而不是更高层框架中,因此将迫使中间件需要重新实现这些常用方法。

context 在每个 request 请求中被创建,在中间件中作为接收器(receiver)来引用,或者通过 this 标识符来引用:

许多 context 的访问器和方法为了便于访问和调用,简单的委托给他们的 ctx.request 和 ctx.response 所对应的等价方法, 比如说 ctx.type 和 ctx.length 代理了 response 对象中对应的方法,ctx.path 和 ctx.method 代理了 request 对象中对应的方法。

KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架之koahub-handlebars

koahub-handlebars

koahub-handlebars

koahub handlebars templates

$ npm install koahub-handlebars
 var koa require(‘koa);
 var hbs require(‘koahub-handlebars);
 
 var app koa();
 
 // koahub-handlebars is middleware. `use` it before you want to render a view 
 app.use(hbs.middleware({
   viewPath__dirname ‘/views
 }));
 
 // Render is attached to the koa context. Call `this.render` in your middleware 
 // to attach rendered html to the koa response body. 
 app.use(function *({
   yield this.render(‘index{title‘koahub-handlebars});
 })
 
 app.listen(3000);
 

Helpers are registered using the #registerHelper method. Here is an example using the default instance (helper stolen from official Handlebars docs:

hbs require(‘koahub-handlebars);
 
hbs.registerHelper(‘linkfunction(texturl{
  text hbs.Utils.escapeExpression(text);
  url  hbs.Utils.escapeExpression(url);
 
  var result ‘<a href="‘ + url ‘">‘ + text ‘</a>;
 
  return new hbs.SafeString(result);
});

Your helper is then accessible in all views by using, {{link "Google" "http://google.com"}}

The registerHelperUtils, and SafeString methods all proxy to an internal Handlebars instance. If passing an alternative instance of Handlebars to the middleware configurator, make sure to do so before registering helpers via the koahub-handlebars proxy of the above functions, or just register your helpers directly via your Handlebars instance.

You can also access the current Koa context in your helper. If you want to have a helper that outputs the current URL, you could write a helper like the following and call it in any template as {{requestURL}}.

hbs.registerHelper(‘requestURL‘, function() {
  var url = hbs.templateOptions.data.koa.request.url;
  return url;
});

The simple way to register partials is to stick them all in a directory, and pass the partialsPath option when generating the middleware. Say your views are in ./views, and your partials are in ./views/partials. Configuring the middleware via

app.use(hbs.middleware({
  viewPath: __dirname + ‘/views‘,
  partialsPath: __dirname + ‘/views/partials‘
}));

will cause them to be automatically registered. Alternatively, you may register partials one at a time by calling hbs.registerPartial which proxies to the cached handlebars #registerPartial method.

Passing defaultLayout with the a layout name will cause all templates to be inserted into the {{{body}}} expression of the layout. This might look like the following.

<!DOCTYPE html>
<html>
<head>
  <title>{{title}}</title>
</head>
<body>
  {{{body}}}
</body>
</html>

In addition to, or alternatively, you may specify a layout to render a template into. Simply specify {{!< layoutName }} somewhere in your template. koahub-handlebars will load your layout from layoutsPath if defined, or from viewPath otherwise.

At this time, only a single content block ({{{body}}}) is supported.

The plan for koahub-handlebars is to offer identical functionality as koa-hbs (eventaully). These options are supported now.

  • viewPath: [required] Full path from which to load templates (Array|String)
  • handlebars: Pass your own instance of handlebars
  • templateOptions: Hash of handlebars options to pass to template()
  • extname: Alter the default template extension (default: ‘.html‘)
  • partialsPath: Full path to partials directory (Array|String)
  • defaultLayout: Name of the default layout
  • layoutsPath: Full path to layouts directory (String)
  • disableCache: Disable template caching (default: ‘.true‘)

Application local variables ([this.state](https://github.com/koajs/koa/blob/master/docs/api/context.md#ctxstate)) are provided to all templates rendered within the application.

app.use(function *(next{
  this.state.title ‘My App;
  this.state.email [email protected];
  yield next;
});

The state object is a JavaScript Object. The properties added to it will be exposed as local variables within your views.

<title>{{title}}</title>
 
<p>Contact : {{email}}</p>

koa-hbs

  1. Configuration file incremental changes
  2. Modify some of the features and the default configuration
  3. ...

 

源码详情:http://js.koahub.com

技术分享

以上是关于koa-基于node.js平台的下一代web开发框架入门的主要内容,如果未能解决你的问题,请参考以下文章

Koa -- 基于 Node.js 平台的下一代 web 开发框架

基于 Koa.js 平台的 Node.js web 快速开发框架KoaHub.js demo 可安装

KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架之koahub

KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架之koahub-handlebars

koa2 从入门到进阶之路

KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架之koahub-skip