koa 的 Context

context上下文对象: 该对象类似原生http中的 req + res
    - 该对象的req,res属性也存在,就是原生没有包装过的req,res
    - 简单说:  context 对象就是从请求到响应 过程中的一个描述对象
  - next函数:调用下一个中间件
- request(请求对象):  其中包含客户端请求的相关信息
- response(响应对象): 包含响应数据的具体操作



#### request常用属性

- ctx.request.url(ctx.url)
- ctx.request.method(ctx.method)
- ctx.request.headers(ctx.headers)



#### response常用属性

- ctx.response.set(ctx.set)  __函数:参数key,val__
- ctx.response.status(ctx.status)

- ctx.response.body(ctx.body)  



#### 小结

- 以上所有使用的属性,都可以简写 ctx.xxx
- 使用async await的应用场景,如果你出现了异步操作,使用其,  后一个中间件使用了async,前后都使用
- 三主角: __函数前面 async, 内部才能await,要想await能有用,就用promise包裹他__

demo 

//引入对象
const Koa = require('koa');
//创建服务器对象
const app = new Koa();
//配置
app.use((ctx,next)=> {
  ctx.body = 'Hello World';
  console.log(ctx.url);   //  /
  console.log(ctx.method);  //   GET
  // { host: 'localhost:8880',
  // 'cache-control': 'max-age=0',
  // 'upgrade-insecure-requests': '1',
  // 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
  // accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  // 'accept-encoding': 'gzip, deflate, br',
  // 'accept-language': 'zh-CN,zh;q=0.9',
  // connection: 'close' }
  console.log(ctx.headers);
  next();

});
// Request URL: http://localhost:8880/
// Request Method: GET
// Status Code: 200 OK
// Remote Address: 127.0.0.1:1080
// Referrer Policy: no-referrer-when-downgrade
// Connection: close
// Content-Length: 18
// Content-Type: text/plain; charset=utf-8
// Date: Tue, 25 Dec 2018 05:24:55 GMT
// Proxy-Connection: keep-alive
// test: 123
app.use((ctx)=>{
   ctx.set('test','123');    //test: 123
   ctx.status=200;   //Status Code: 200 OK
   ctx.body=`<h1>大家好</h1>`  //<h1>大家好</h1>
})
app.listen(8880,(req,res)=>{
     console.log('服务器已经启动了 ')
})

截图:

猜你喜欢

转载自www.cnblogs.com/guangzhou11/p/10173403.html
koa