KOA 学习(二)

app.listen(...)

Koa 应用并不是是一个 1-to-1 表征关系的 HTTP 服务器。 一个或多个Koa应用能够被挂载到一块儿组成一个包含单一 HTTP 服务器的大型应用群。css

var koa = require('koa');
var app = koa();
app.listen(3000);

app.listen(...) 其实是如下代码的语法糖:node

var http = require('http');
var koa = require('koa');
var app = koa();
http.createServer(app.callback()).listen(3000);

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

const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
http.createServer(app.callback()).listen(3001);

app.callback()

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

/**
 * Create HTTP server.
 */

var server = http.createServer(app.callback());

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

app.use(function)

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

app.keys=

设置签名Cookie密钥,该密钥会被传递给 KeyGripapi

固然,您也能够本身生成 KeyGrip 实例:服务器

app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');

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

ctx.cookies.set('name', 'tobi', { signed: true });

app.context

app.context 是ctx中创造来的,你能够对经过app.context ctx增长属性。这是一个颇有用的属性用来贯穿你的整个app.app.context is the prototype from which ctx is created from. You may add additional properties to ctx by editing app.context. This is useful for adding properties or methods to ctx to be used across your entire app, which may be more performant (no middleware) and/or easier (fewer require()s) at the expense of relying more on ctx, which could be considered an anti-pattern.app

app.context.db = db();

app.use(async (ctx) => {
  console.log(ctx.db);
});

错误处理

默认状况下Koa会将全部错误信息输出到 stderr,除非 NODE_ENV 是 "test"。为了实现自定义错误处理逻辑(好比 centralized logging),您能够添加 "error" 事件监听器。框架

app.on('error', function(err){
  log.error('server error', err);
});

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

app.on('error', function(err, ctx){
  log.error('server error', err, ctx);
});

当发生错误但仍可以响应客户端时(好比没有数据写到socket中),Koa会返回一个500错误(Internal Server Error)。

不管哪一种状况,Koa都会生成一个应用级别的错误信息,以便实现日志记录等目的。

 

Context(上下文)

Koa Context 将 node 的 request 和 response 对象封装在一个单独的对象里面,其为编写 web 应用和 API 提供了不少有用的方法。

这些操做在 HTTP 服务器开发中常常使用,所以其被添加在上下文这一层,而不是更高层框架中,所以将迫使中间件须要从新实现这些经常使用方法。

context 在每一个 request 请求中被建立,在中间件中做为接收器(receiver)来引用.

在KOA1.0中

app.use(function *(){
  this; // is the Context
  this.request; // is a koa Request
  this.response; // is a koa Response
});

在KOA2.0中

app.use(async (ctx, next) => {
  ctx; // is the Context
  ctx.request; // is a koa Request
  ctx.response; // is a koa Response
});

API

Context 详细的方法和访问器。

ctx.req

Node 的 request 对象。

ctx.res

Koa 不支持 直接调用底层 res 进行响应处理。请避免使用如下 node 属性:

res.statusCode,res.writeHead(),res.write(),res.end()

ctx.request

Koa 的 Request 对象。

ctx.response

Koa 的 Response 对象。

ctx.app

应用实例引用。

ctx.cookies.get(name, [options])

得到 cookie 中名为 name 的值,options 为可选参数:

  • 'signed': 若是为 true,表示请求时 cookie 须要进行签名。

注意:Koa 使用了 Express 的 cookies 模块,options 参数只是简单地直接进行传递。

ctx.cookies.set(name, value, [options])

设置 cookie 中名为 name 的值,options 为可选参数:

  • signed: 是否要作签名
  • expires: cookie 有效期时间
  • path: cookie 的路径,默认为 /'
  • domain: cookie 的域
  • secure: false 表示 cookie 经过 HTTP 协议发送,true 表示 cookie 经过 HTTPS 发送。
  • httpOnly: true 表示 cookie 只能经过 HTTP 协议发送

注意:Koa 使用了 Express 的 cookies 模块,options 参数只是简单地直接进行传递。

  if ( req.url == "/set" ) {
    cookies
      // set a regular cookie
      .set( "unsigned", "foo", { httpOnly: false } )

      // set a signed cookie
      .set( "signed", "bar", { signed: true } )

      // mimic a signed cookie, but with a bogus signature
      .set( "tampered", "baz" )
      .set( "tampered.sig", "bogus" )

    res.writeHead( 302, { "Location": "/" } )
    return res.end( "Now let's check." )
  }

ctx.throw(msg, [status])

抛出包含 .status 属性的错误,默认为 500。该方法可让 Koa 准确的响应处理状态。 Koa支持如下组合:

 

ctx.throw(403);
ctx.throw('name required', 400);
ctx.throw(400, 'name required');
ctx.throw('something exploded');

ctx.respond

为了不使用 Koa 的内置响应处理功能,您能够直接赋值 this.repond = false;。若是您不想让 Koa 来帮助您处理 reponse,而是直接操做原生 res 对象,那么请使用这种方法。

注意: 这种方式是不被 Koa 支持的。其可能会破坏 Koa 中间件和 Koa 自己的一些功能。其只做为一种 hack 的方式,并只对那些想要在 Koa 方法和中间件中使用传统 fn(req, res) 方法的人来讲会带来便利。

Request aliases

如下访问器和别名与 Request 等价:

  • ctx.header
  • ctx.method
  • ctx.method=
  • ctx.url
  • ctx.url=
  • ctx.originalUrl
  • ctx.path
  • ctx.path=
  • ctx.query
  • ctx.query=
  • ctx.querystring
  • ctx.querystring=
  • ctx.host
  • ctx.hostname
  • ctx.fresh
  • ctx.stale
  • ctx.socket
  • ctx.protocol
  • ctx.secure
  • ctx.ip
  • ctx.ips
  • ctx.subdomains
  • ctx.is()
  • ctx.accepts()
  • ctx.acceptsEncodings()
  • ctx.acceptsCharsets()
  • ctx.acceptsLanguages()
  • ctx.get()

Response aliases

如下访问器和别名与 Response 等价:

  • ctx.body
  • ctx.body=
  • ctx.status
  • ctx.status=
  • ctx.length=
  • ctx.length
  • ctx.type=
  • ctx.type
  • ctx.headerSent
  • ctx.redirect()
  • ctx.attachment()
  • ctx.set()
  • ctx.remove()
  • ctx.lastModified=
  • ctx.etag=
相关文章
相关标签/搜索