Context 上下文

1. 了解Context

Koa Context 将 node 的 request 和 response 对象封装在一个单独的对象里面,其为编写 web 应用和 API 提供了很多有用的方法。
context 在每个 request 请求中被创建,在中间件中作为接收器(receiver)来引用,或者通过 this 标识符来引用:

  1. app.use(async ctx => {
  2. ctx; // is the Context
  3. ctx.request; // is a koa Request
  4. ctx.response; // is a koa Response
  5. });

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

2. Context API

| API | 描述 | | —- | —- |

| ctx.req | request 对象. |

| ctx.res | response 对象. |

| ctx.request | Request 对象. |

| ctx.response | Response 对象. |

| ctx.cookies.get(name, [options]) | 通过 options 获取 cookie name: |

| ctx.cookies.set(name, value, [options]) | 通过 options 设置 cookie name 的 value : |

3.Response 别名

以下访问器和 Response 别名等效:

  • ctx.status
  • ctx.message
  • ctx.length
  • ctx.type
  • ctx.redirect()

4. ctx的属性与方法

4.1 向前端返回数据

ctx.body

  1. ctx.body = '返回数据';
  2. //也可以对象
  3. ctx.body = {
  4. a:1
  5. }
  6. //Koa会将对象封装成字符串传递个前端
4.2 获取前端路径

ctx.url
等同于ctx.request.url

  1. //比如 网址输入localhost:3000/path?name=wuwei&age=18
  2. //返回 /path?name=wuwei&age=18
  3. app.use(async function(ctx,next){
  4. // 请求路径
  5. console.log(ctx.url);
  6. ctx.body='hello wrold'
  7. })
4.3 获取请求的方法

ctx.method

  1. app.use(async function(ctx,next){
  2. // 请求方式
  3. console.log(ctx.method);
  4. ctx.body='htllo world'
  5. })
4.4 中间件之间的传值

用于通过中间件传递信息和你的前端视图。
ctx.state

4.5 获取非查询的路由

ctx.path

  1. //比如 网址输入localhost:3000/path?name=wuwei&age=18
  2. ctx.path;
  3. //返回 /path
4.6 将路由中的查询部分转成对象

ctx.query

  1. //比如 网址输入localhost:3000/path?name=wuwei&age=18
  2. //返回 { name:wuwei,age:18 }
  3. app.use(function(ctx,next){
  4. // 获取querystring解析后的对象
  5. console.log(ctx.query);
  6. ctx.body='hello world'
  7. })
4.7 只获取路由中查询部分

ctx.querystring

  1. //比如 网址输入localhost:3000/path?name=wuwei&age=18
  2. //返回 name=wuwei&age=18
  3. app.use(function(ctx,next){
  4. // 后去queryString
  5. console.log(ctx.querystring);
  6. ctx.body='hello world'
4.8. 设置返回给前端的响应头
  1. // 响应状态
  2. ctx.status = 201
  3. // 响应类型
  4. ctx.type = 'html'
  5. // 返回数据
  6. ctx.body = '<h1>h1</h1>'