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
2、ctx结构
{ 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>'
}
3、ctx常用API
Request 别名
ctx.header
ctx.headers
ctx.method
ctx.method=
ctx.url
ctx.url=
ctx.path
ctx.path=
ctx.query
ctx.query=
ctx.host
ctx.hostname
ctx.socket
ctx.protocol
ctx.secure
ctx.ip
ctx.ips
ctx.params
Response 别名
ctx.body
ctx.body=
ctx.status
ctx.status=
ctx.message
ctx.message=
学习链接:
https://www.cnblogs.com/lfri/p/11936231.html
https://koa.bootcss.com/#context