koa2入门笔记

一 什么是koa

koa是基于nodejs的web框架, 是一个中间件框架。

二 中间件

Koa 中间件是简单的函数,它是带有 (ctx, next)形参 的函数

可以采用两种不同的方法来实现中间件 async function和 common function。编写中间件的最佳做法为使用async function。

ctx(上下文-Context):

每个请求都将创建一个 Context,并在中间件中作为接收器引用,即每个中间件都接收一个 Koa 的 Context 对象,ctx 只是通常为上下文对象的参数名称

Context 具体方法和访问器

此笔记值列举写常用的属性:

ctx.req:

Node 的 request 对象

ctx.res:

Node 的 response 对象.

​ 绕过 Koa 的 response 处理是 不被支持的. 应避免使用以下 node 属性:

​ res.statusCode; res.writeHead(); res.write(); res.end()

Context 对象 将 node 的 requestresponse 对象封装到单个对象中:

ctx.request:

Koa 提供了一个 Request 对象作为 Contextrequest 属性。 Koa的 Request 对象提供了用于处理 http 请求的方法,该请求委托给 node http 模块的IncomingMessage

request.url #获取请求 URL.

http://example.com/foo/bar?q=1
url为/foo/bar?q=1

request.originalUrl #获取请求原始URL。

request.origin

获取URL的来源,包括 protocolhost

ctx.request.origin
// => http://example.com

request.href

获取完整的请求URL,包括 protocolhosturl

ctx.request.href;
// => http://example.com/foo/bar?q=1

request.method #请求方法。

request.header #请求标头对象。这与 node http.IncomingMessage 上的 headers 字段相同

request.path #获取请求路径名。

request.query

#获取解析的查询字符串, 当没有查询字符串时,返回一个空对象。

例如 “color=blue&size=small”:

{
  color: 'blue',
  size: 'small'
}

request.querystring #根据 ? 获取原始查询字符串.

request.type

#获取请求 Content-Type 不含参数 “charset”。

const ct = ctx.request.type;
// => "image/png"

request.charset

在存在时获取请求字符集,或者 undefined

ctx.request.charset;
// => "utf-8"

request.accepts(types)

检查给定的 type(s) 是否可以接受,如果 true,返回最佳匹配,否则为 false

ctx.respons:

Koa提供了一个 Response 对象作为 Contextresponse 属性。 Koa的 Response 对象提供了用于处理 http 响应的方法,该响应委托给 ServerResponse

#response.body

将响应体设置为以下之一:如果 response.status 未被设置, Koa 将会自动设置状态为 200204

1.string

Content-Type 默认为 text/htmltext/plain, 同时默认字符集是 utf-8。Content-Length 字段也是如此。

2.Object,Array JSON-字符串化

Content-Type 默认为 application/json. 这包括普通的对象 { foo: 'bar' } 和数组 ['foo', 'bar']

3.Buffer 写入

Content-Type 默认为 application/octet-stream, 并且 Content-Length 字段也是如此。

4.Stream 管道

Content-Type 默认为 application/octet-stream

5.null 无内容响应

#response.status

通过数字代码设置响应状态,默认情况下,response.status 设置为 404

#response.type

设置响应 Content-Type 通过 mime 字符串或文件扩展名。

ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.state:

推荐的命名空间,用于通过中间件传递信息和你的前端视图。

ctx.state.user = await User.find(id);
ctx.throw:

ctx.throw([status], [msg], [properties]):

status:转态码

msg:自定义的错误信息,适用于客户端响应,这通常不是错误消息的内容,因为您不想泄漏故障详细信息。

ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });
ctx.app:

应用程序实例引用

ctx.assert:

ctx.assert(value, [status], [msg], [properties])

!value 时,Helper 方法抛出类似于 .throw() 的错误。这与 node 的 assert() 方法类似.

ctx.assert(ctx.state.user, 401, 'User not found. Please login!');

为方便起见许多上下文的访问器和方法直接委托给它们的 ctx.requestctx.response ,不然的话它们是相同的。 例如 ctx.typectx.length 委托给 response 对象,ctx.pathctx.method 委托给 request

next:

next 是调用执行下游中间件的函数. 在代码执行完成后通过 then 方法返回一个 Promise.

洋葱模型

Koa 的中间件之间按照编码顺序在栈内依次执行,允许您执行操作并向下传递请求(downstream),之后过滤并逆序返回响应(upstream)。

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx,next)=>{
    console.log(1)
    //next是一个异步函数,返回一个promise
    //如果不写next,这个路由被匹配后就停止,不会匹配下面的路由.
    await next();//该函数暂停并将控制传递给定义的下一个中间件。
    console.log(4);
    ctx.body = 'hello restful-API';
});

app.use(async (ctx,next)=>{
    console.log(2);
    await next();
    console.log(3)
});

app.listen(3000)

// 打印执行顺序为 1,2,3,4

三 Koa 应用程序

在执行 new Koa() 时创建的对象被称为 Koa 应用对象。

Koa 应用程序是一个包含一组中间件函数的对象,它是按照类似堆栈的方式组织和执行的。

设置

应用程序设置是 app 实例上的属性,目前支持如下:

  • app.env 默认是 NODE_ENV 或 “development”
  • app.keys 签名的 cookie 密钥数组
  • app.proxy 当真正的代理头字段将被信任时
  • app.subdomainOffset 对于要忽略的 .subdomains 偏移[2]
  const Koa = require('koa');
  const app = new Koa();
  app.proxy = true;

app.listen(…)

应用程序被绑定到 3000 端口。

Koa 应用程序不是 HTTP 服务器的1对1展现。 可以将一个或多个 Koa 应用程序安装在一起以形成具有单个HTTP服务器的更大应用程序。

这意味着您可以将同一个应用程序同时作为 HTTP 和 HTTPS 或多个地址:

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

app.use(function)

将给定的中间件方法添加到此应用程序。

代码示例:匹配任何路由的中间件

const Koa = require('koa');
const app = new Koa();
//1. Koa 是一个中间件框架,Koa应用程序是一个包含一组中间件函数的对象

//2. app.use(function) app.use添加一个中间件,并将给定的中间件方法添加到此应用程序。

//3. ctx context 包含request和respond等数据
// 应用级中间件,匹配任何路由
app.use(async (ctx,next)=>{
    //响应数据,相当于原声的res.end(),res.wirte()
    ctx.body = 'hello restful-API';
});

// 监听端口
app.listen(3000);

注:本笔记整理的知识来源,koa中文文档。本文档只是对中文文档的总结梳理,加些通俗的表达,使之更加容易理解。

猜你喜欢

转载自www.cnblogs.com/liangsf/p/11879209.html