KOA 学习(二)

app.listen(...)

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

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

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

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

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

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 应用上。

/**
 * 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)

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

app.keys=

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

当然,您也可以自己生成 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 的时候,才会使用密钥进行加密:

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.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=
原文地址:https://www.cnblogs.com/myzy/p/6510454.html