为了试图搞明白,用console.log将它输出
const Koa = require('koa'); const app = new Koa(); app.use(ctx => { ctx.body = 'Hello Koa in app-async.js'; console.log(ctx) }); app.listen(3000);
打印的结果如下:
{ request: { method: 'GET', url: '/', header: { host: 'localhost:3000', connection: 'keep-alive', 'cache-control': 'max-age=0', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'accept-encoding': 'gzip, deflate, sdch, br', 'accept-language': 'zh-CN,zh;q=0.8' } }, response: { status: 200, message: 'OK', header: { 'content-type': 'text/plain; charset=utf-8', 'content-length': '25' } }, app: { subdomainOffset: 2, proxy: false, env: 'development' }, originalUrl: '/', req: '<original node req>', res: '<original node res>', socket: '<original node socket>' }
可见它主要包括request和response两部分。
ctx是context的缩写中文一般叫成上下文,这个在所有语言里都有的名词,可以理解为上(request)下(response)沟通的环境,所以koa中把他们两都封装进了ctx对象,koa官方文档里的解释是为了调用方便,ctx.req=ctx.request,ctx.res=ctx.response,类似linux系统中的软连接?最终执行还是request和response对象
body是http协议中的响应体,header是指响应头
ctx.body = ctx.res.body = ctx.response.body
Koa 提供一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。
Context.response.body
属性就是发送给用户的内容。
const Koa = require('koa'); const app = new Koa(); const main = ctx => { ctx.response.body = 'Hello World'; }; app.use(main); app.listen(3000);
上面代码中,main
函数用来设置ctx.response.body
。然后,使用app.use
方法加载main
函数。
你可能已经猜到了,ctx.response
代表 HTTP Response。同样地,ctx.request
代表 HTTP Request。
运行这个 demo,访问 http://127.0.0.1:3000 ,现在就可以看到"Hello World"了。
参考链接:
1. segmentfault: https://segmentfault.com/q/1010000008379638
2. ruanyifeng博客: http://www.ruanyifeng.com/blog/2017/08/koa.html
3. github官方解释:https://github.com/ruanyf/koa-demos/blob/master/demos/21.js