koa2中的ctx是什么?


為了試圖搞明白,用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM