Context 上下文
1. 了解Context
Koa Context 将 node 的 request 和 response 对象封装在一个单独的对象里面,其为编写 web 应用和 API 提供了很多有用的方法。context 在每个 request 请求中被创建,在中间件中作为接收器(receiver)来引用,或者通过 this 标识符来引用:
app.use(async ctx => {ctx; // is the Contextctx.request; // is a koa Requestctx.response; // is a koa Response});
许多 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
ctx.body = '返回数据';//也可以对象ctx.body = {a:1}//Koa会将对象封装成字符串传递个前端
4.2 获取前端路径
ctx.url
等同于ctx.request.url
//比如 网址输入localhost:3000/path?name=wuwei&age=18//返回 /path?name=wuwei&age=18app.use(async function(ctx,next){// 请求路径console.log(ctx.url);ctx.body='hello wrold'})
4.3 获取请求的方法
ctx.method
app.use(async function(ctx,next){// 请求方式console.log(ctx.method);ctx.body='htllo world'})
4.4 中间件之间的传值
用于通过中间件传递信息和你的前端视图。ctx.state
4.5 获取非查询的路由
ctx.path
//比如 网址输入localhost:3000/path?name=wuwei&age=18ctx.path;//返回 /path
4.6 将路由中的查询部分转成对象
ctx.query
//比如 网址输入localhost:3000/path?name=wuwei&age=18//返回 { name:wuwei,age:18 }app.use(function(ctx,next){// 获取querystring解析后的对象console.log(ctx.query);ctx.body='hello world'})
4.7 只获取路由中查询部分
ctx.querystring
//比如 网址输入localhost:3000/path?name=wuwei&age=18//返回 name=wuwei&age=18app.use(function(ctx,next){// 后去queryStringconsole.log(ctx.querystring);ctx.body='hello world'
4.8. 设置返回给前端的响应头
// 响应状态ctx.status = 201// 响应类型ctx.type = 'html'// 返回数据ctx.body = '<h1>h1</h1>'
