koa中的ctx里面是什么

koa这个框架其实一个比较关键的参数就是ctx,这里封装了一些客户的请求方法,同时还包括一些服务器返回给客户的方法。我们通过输出来看看他里面是些什么玩意儿。

console.log("======================dd");
console.log(ctx);
console.log("======================11");
console.log(ctx.request);
console.log("======================2");
console.log(ctx.request.query);
console.log("======================3");
======================dd
{
    
    
  request: {
    
    
    method: 'GET',
    url: '/?name=show',
    header: {
    
    
      host: 'localhost:3000',
      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0',
      accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
      'accept-language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
      'accept-encoding': 'gzip, deflate, br',
      connection: 'keep-alive',
      'upgrade-insecure-requests': '1',
      'sec-fetch-dest': 'document',
      'sec-fetch-mode': 'navigate',
      'sec-fetch-site': 'none',
      'sec-fetch-user': '?1'
    }
  },
  response: {
    status: 404,
    message: 'Not Found',
    header: [Object: null prototype] {}
  },
  app: { subdomainOffset: 2, proxy: false, env: 'development' },
  originalUrl: '/?name=show',
  req: '<original node req>',
  res: '<original node res>',
  socket: '<original node socket>'
}
======================11
{
  method: 'GET',
  url: '/?name=show',
  header: {
    host: 'localhost:3000',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0',
    accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'accept-language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    'accept-encoding': 'gzip, deflate, br',
    connection: 'keep-alive',
    'upgrade-insecure-requests': '1',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'sec-fetch-user': '?1'
  }
}
======================2
[Object: null prototype] {
    
     name: 'show' }
======================3

从上面的输出来看,ctx是一个对象,这个对象包括rquest和response两个属性。因此我们可以通过ctx.request.url及ctx.request.method来输出相应的属性值。
ctx.request
ctx.request.url
ctx.request.query
ctx.request.querystring
ctx.request.method
ctx.request.path
ctx.request.on(‘data’, func)
ctx.request.accepts()

ctx.response
ctx.response.body
ctx.response.status
ctx.response.type
ctx.response.redirect(url, [alt])

猜你喜欢

转载自blog.csdn.net/weixin_36557877/article/details/129300674
今日推荐