# 請求(Request)
Koa `Request` 對象是對 node 的 request 進一步抽象和封裝,提供了日常 HTTP 服務器開發中一些有用的功能。
## API
### req.header
請求頭對象
### req.method
請求方法
### req.method=
設置請求方法,在實現中間件時非常有用,比如 `methodOverride()`。
### req.length
以數字的形式返回 request 的內容長度(Content-Length),或者返回 `undefined`。
### req.url
獲得請求url地址。
### req.url=
設置請求地址,用于重寫url地址時。
### req.originalUrl
獲取請求原始地址。
### req.path
獲取請求路徑名。
### req.path=
設置請求路徑名,并保留請求參數(就是url中?后面的部分)。
### req.querystring
獲取查詢參數字符串(url中?后面的部分),不包含 ?。
### req.querystring=
設置查詢參數。
### req.search
獲取查詢參數字符串,包含 ?。
### req.search=
設置查詢參數字符串。
### req.host
獲取 host (hostname:port)。 當 `app.proxy` 設置為 **true** 時,支持 `X-Forwarded-Host`。
### req.hostname
獲取 hostname。當 `app.proxy` 設置為 **true** 時,支持 `X-Forwarded-Host`。
### req.type
獲取請求 `Content-Type`,不包含像 "charset" 這樣的參數。
```
var ct = this.request.type;
// => "image/png"
```
### req.charset
獲取請求 charset,沒有則返回 `undefined`:
```
this.request.charset
// => "utf-8"
```
### req.query
將查詢參數字符串進行解析并以對象的形式返回,如果沒有查詢參數字字符串則返回一個空對象。
注意:該方法**不**支持嵌套解析。
比如 "color=blue&size=small":
```
{
color: 'blue',
size: 'small'
}
```
### req.query=
根據給定的對象設置查詢參數字符串。
注意:該方法不支持嵌套對象。
```
this.query = { next: '/login' };
```
### req.fresh
檢查請求緩存是否 "fresh"(內容沒有發生變化)。該方法用于在 `If-None-Match` / `ETag`, `If-Modified-Since` 和 `Last-Modified` 中進行緩存協調。當在 response headers 中設置一個或多個上述參數后,該方法應該被使用。
```
this.set('ETag', '123');
// cache is ok
if (this.fresh) {
this.status = 304;
return;
}
// cache is stale
// fetch new data
this.body = yield db.find('something');
```
### req.stale
與 `req.fresh` 相反。
### req.protocol
返回請求協議,"https" 或者 "http"。 當 `app.proxy` 設置為 **true** 時,支持 `X-Forwarded-Host`。
### req.secure
簡化版 `this.protocol == "https"`,用來檢查請求是否通過 TLS 發送。
### req.ip
請求遠程地址。 當 `app.proxy` 設置為 **true** 時,支持 `X-Forwarded-Host`。
### req.ips
當 `X-Forwarded-For` 存在并且 `app.proxy` 有效,將會返回一個有序(從 upstream 到 downstream)ip 數組。 否則返回一個空數組。
### req.subdomains
以數組形式返回子域名。
子域名是在host中逗號分隔的主域名前面的部分。默認情況下,應用的域名假設為host中最后兩部分。其可通過設置 `app.subdomainOffset` 進行更改。
舉例來說,如果域名是 "tobi.ferrets.example.com":
如果沒有設置 `app.subdomainOffset`,其 subdomains 為 `["ferrets", "tobi"]`。 如果設置 `app.subdomainOffset` 為3,其 subdomains 為 `["tobi"]`。
### req.is(type)
檢查請求所包含的 "Content-Type" 是否為給定的 type 值。 如果沒有 request body,返回 `undefined`。 如果沒有 content type,或者匹配失敗,返回 `false`。 否則返回匹配的 content-type。
```
// With Content-Type: text/html; charset=utf-8
this.is('html'); // => 'html'
this.is('text/html'); // => 'text/html'
this.is('text/*', 'text/html'); // => 'text/html'
// When Content-Type is application/json
this.is('json', 'urlencoded'); // => 'json'
this.is('application/json'); // => 'application/json'
this.is('html', 'application/*'); // => 'application/json'
this.is('html'); // => false
```
比如說您希望保證只有圖片發送給指定路由:
```
if (this.is('image/*')) {
// process
} else {
this.throw(415, 'images only!');
}
```
### Content Negotiation
Koa `request` 對象包含 content negotiation 功能(由 [accepts](http://github.com/expressjs/accepts) 和 [negotiator](https://github.com/federomero/negotiator) 提供):
* `req.accepts(types)`
* `req.acceptsEncodings(types)`
* `req.acceptsCharsets(charsets)`
* `req.acceptsLanguages(langs)`
如果沒有提供 types,將會返回**所有的**可接受類型。
如果提供多種 types,將會返回最佳匹配類型。如果沒有匹配上,則返回 `false`,您應該給客戶端返回 `406 "Not Acceptable"`。
為了防止缺少 accept headers 而導致可以接受任意類型,將會返回第一種類型。因此,您提供的類型順序非常重要。
### req.accepts(types)
檢查給定的類型 `types(s)` 是否可被接受,當為 true 時返回最佳匹配,否則返回 `false`。`type` 的值可以是一個或者多個 mime 類型字符串。 比如 "application/json" 擴展名為 "json",或者數組 `["json", "html", "text/plain"]`。
```
// Accept: text/html
this.accepts('html');
// => "html"
// Accept: text/*, application/json
this.accepts('html');
// => "html"
this.accepts('text/html');
// => "text/html"
this.accepts('json', 'text');
// => "json"
this.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
this.accepts('image/png');
this.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
this.accepts(['html', 'json']);
this.accepts('html', 'json');
// => "json"
// No Accept header
this.accepts('html', 'json');
// => "html"
this.accepts('json', 'html');
// => "json"
```
`this.accepts()` 可以被調用多次,或者使用 switch:
```
switch (this.accepts('json', 'html', 'text')) {
case 'json': break;
case 'html': break;
case 'text': break;
default: this.throw(406, 'json, html, or text only');
}
```
### req.acceptsEncodings(encodings)
檢查 `encodings` 是否可以被接受,當為 `true` 時返回最佳匹配,否則返回 `false`。 注意:您應該在 encodings 中包含 `identity`。
```
// Accept-Encoding: gzip
this.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"
this.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"
```
當沒有傳遞參數時,返回包含所有可接受的 encodings 的數組:
```
// Accept-Encoding: gzip, deflate
this.acceptsEncodings();
// => ["gzip", "deflate", "identity"]
```
注意:如果客戶端直接發送 `identity;q=0` 時,`identity` encoding(表示no encoding) 可以不被接受。雖然這是一個邊界情況,您仍然應該處理這種情況。
### req.acceptsCharsets(charsets)
檢查 `charsets` 是否可以被接受,如果為 `true` 則返回最佳匹配, 否則返回 `false`。
```
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"
this.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"
```
當沒有傳遞參數時, 返回包含所有可接受的 charsets 的數組:
```
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]
```
### req.acceptsLanguages(langs)
檢查 `langs` 是否可以被接受,如果為 `true` 則返回最佳匹配,否則返回 `false`。
```
// Accept-Language: en;q=0.8, es, pt
this.acceptsLanguages('es', 'en');
// => "es"
this.acceptsLanguages(['en', 'es']);
// => "es"
```
當沒有傳遞參數時,返回包含所有可接受的 langs 的數組:
```
// Accept-Language: en;q=0.8, es, pt
this.acceptsLanguages();
// => ["es", "pt", "en"]
```
### req.idempotent
檢查請求是否為冪等(idempotent)。
### req.socket
返回請求的socket。
### req.get(field)
返回請求 header 中對應 field 的值。