# Context(上下文)
Koa Context 將 node 的 `request` 和 `response` 對象封裝在一個單獨的對象里面,其為編寫 web 應用和 API 提供了很多有用的方法。
這些操作在 HTTP 服務器開發中經常使用,因此其被添加在上下文這一層,而不是更高層框架中,因此將迫使中間件需要重新實現這些常用方法。
`context` 在每個 request 請求中被創建,在中間件中作為接收器(receiver)來引用,或者通過 `this` 標識符來引用:
```
app.use(function *(){
this; // is the Context
this.request; // is a koa Request
this.response; // is a koa Response
});
```
許多 context 的訪問器和方法為了便于訪問和調用,簡單的委托給他們的 `ctx.request` 和 `ctx.response` 所對應的等價方法, 比如說 `ctx.type` 和 `ctx.length` 代理了 `response` 對象中對應的方法,`ctx.path` 和 `ctx.method` 代理了 `request` 對象中對應的方法。
## API
`Context` 詳細的方法和訪問器。
### ctx.req
Node 的 `request` 對象。
### ctx.res
Node 的 `response` 對象。
Koa _不支持_ 直接調用底層 res 進行響應處理。請避免使用以下 node 屬性:
* `res.statusCode`
* `res.writeHead()`
* `res.write()`
* `res.end()`
### ctx.request
Koa 的 `Request` 對象。
### ctx.response
Koa 的 `Response` 對象。
### ctx.app
應用實例引用。
### ctx.cookies.get(name, [options])
獲得 cookie 中名為 `name` 的值,`options` 為可選參數:
* 'signed': 如果為 true,表示請求時 cookie 需要進行簽名。
注意:Koa 使用了 Express 的 [cookies](https://github.com/jed/cookies) 模塊,options 參數只是簡單地直接進行傳遞。
### ctx.cookies.set(name, value, [options])
設置 cookie 中名為 `name` 的值,`options` 為可選參數:
* `signed`: 是否要做簽名
* `expires`: cookie 有效期時間
* `path`: cookie 的路徑,默認為 `/'`
* `domain`: cookie 的域
* `secure`: false 表示 cookie 通過 HTTP 協議發送,true 表示 cookie 通過 HTTPS 發送。
* `httpOnly`: true 表示 cookie 只能通過 HTTP 協議發送
注意:Koa 使用了 Express 的 [cookies](https://github.com/jed/cookies) 模塊,options 參數只是簡單地直接進行傳遞。
### ctx.throw(msg, [status])
拋出包含 `.status` 屬性的錯誤,默認為 `500`。該方法可以讓 Koa 準確的響應處理狀態。 Koa支持以下組合:
```
this.throw(403)
this.throw('name required', 400)
this.throw(400, 'name required')
this.throw('something exploded')
```
`this.throw('name required', 400)` 等價于:
```
var err = new Error('name required');
err.status = 400;
throw err;
```
注意:這些用戶級錯誤被標記為 `err.expose`,其意味著這些消息被準確描述為對客戶端的響應,而并非使用在您不想泄露失敗細節的場景中。
### ctx.respond
為了避免使用 Koa 的內置響應處理功能,您可以直接賦值 `this.repond = false;`。如果您不想讓 Koa 來幫助您處理 reponse,而是直接操作原生 `res` 對象,那么請使用這種方法。
注意: 這種方式是不被 Koa 支持的。其可能會破壞 Koa 中間件和 Koa 本身的一些功能。其只作為一種 hack 的方式,并只對那些想要在 Koa 方法和中間件中使用傳統 `fn(req, res)` 方法的人來說會帶來便利。
## Request aliases
以下訪問器和別名與 [Request](#request) 等價:
* `ctx.header`
* `ctx.method`
* `ctx.method=`
* `ctx.url`
* `ctx.url=`
* `ctx.originalUrl`
* `ctx.path`
* `ctx.path=`
* `ctx.query`
* `ctx.query=`
* `ctx.querystring`
* `ctx.querystring=`
* `ctx.host`
* `ctx.hostname`
* `ctx.fresh`
* `ctx.stale`
* `ctx.socket`
* `ctx.protocol`
* `ctx.secure`
* `ctx.ip`
* `ctx.ips`
* `ctx.subdomains`
* `ctx.is()`
* `ctx.accepts()`
* `ctx.acceptsEncodings()`
* `ctx.acceptsCharsets()`
* `ctx.acceptsLanguages()`
* `ctx.get()`
## Response aliases
以下訪問器和別名與 [Response](#response) 等價:
* `ctx.body`
* `ctx.body=`
* `ctx.status`
* `ctx.status=`
* `ctx.length=`
* `ctx.length`
* `ctx.type=`
* `ctx.type`
* `ctx.headerSent`
* `ctx.redirect()`
* `ctx.attachment()`
* `ctx.set()`
* `ctx.remove()`
* `ctx.lastModified=`
* `ctx.etag=`