问题描述
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);
ctx是上下文的意思,但它究竟是什么呢?为了试图搞明白,用console.log将它输出,但是返回的内容里并没有ctx或content之类的东西。
{ 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>’ }
ctx是什么?ctx.body又是什么?为什么是body?我试过写成ctx.head,会报错~如果换成ctx.response.body这样写,输出结果貌似是一样的,它们两个是等价的吗?
谢谢~
问题解答
回答1: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
更详细看github上的官方文档吧https://github.com/koajs/koa/...
回答2:https://github.com/koajs/koa/...
ctx.body 就是 ctx.response.body 的别名而已。
Response aliasesctx.body
ctx.body=
ctx.status
ctx.status=
ctx.message
ctx.message=
ctx.length=
ctx.length
ctx.type=
ctx.type
ctx.headerSent
ctx.redirect()
ctx.attachment()
ctx.set()
ctx.append()
ctx.remove()
ctx.lastModified=
ctx.etag=
回答3:它是Web框架,专注HTTP生命周期即同意请求到响应结束,CTX指的HTTP生命周期的上下文