koa常用api文檔整理


koa 支持的配置

1.應用配置是 app 實例屬性,目前支持的配置項如下
配置項名稱 簡介
app.name 應用名稱(可選項)
app.env 默認為 NODE_ENV 或者 development
app.proxy 如果為 true,則解析 "Host" 的 header 域,並支持 X-Forwarded-Host
app.subdomainOffset 默認為2,表示 .subdomains 所忽略的字符偏移量。

2.上下文相關
 api         簡介
ctx.req        Node 的 request 對象
ctx.res    Node 的 response 對象
ctx.request    Koa 的 Request 對象。
ctx.response    Koa 的 Response對象
ctx.app      應用實例引用。    
 ctx.cookies.get(name, [options]) 獲得 cookie 中名為 name 的值,
options 為可選參數:
'signed': 如果為 true,
表示請求時 cookie 需要進行簽名,

注意:Koa 使用了 Express 的 cookies 模塊,options 參數只是簡單地直接進行傳遞
ctx.cookies.set(name, value, [options]) 設置 cookie 中名為 name 的值,
options 為可選參數:
1.signed: 是否要做簽名;
2.
expires: cookie 有效期時間;
3.path: cookie 的路徑,默認為 /';domain: cookie 的域;
4.secure: false 表示 cookie 通過 HTTP 協議發送,true 表示 cookie 通過 HTTPS 發送。
5.httpOnly: true 表示 cookie 只能通過 HTTP 協議發送;

注意:Koa 使用了 Express 的 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')
注意:這些用戶級錯誤被標記為 err.expose,其意味着這些消息被准確描述為對客戶端的響應,而並非使用在您不想泄露失敗細節的場景中。

ctx.respond
為了避免使用 Koa 的內置響應處理功能,您可以直接賦值 this.repond = false;。如果您不想讓 Koa 來幫助您處理 reponse,而是直接操作原生 res 對象,那么請使用這種方法。 注意: 這種方式是不被 Koa 支持的。其可能會破壞 Koa 中間件和 Koa 本身的一些功能。其只作為一種 hack 的方式,並只對那些想要在 Koa 方法和中間件中使用傳統 fn(req, res) 方法的人來說會帶來便利。
3. 請求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:
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.ip 請求遠程地址。 當 app.proxy 設置為 true 時,支持 X-Forwarded-Host。
req.secure 簡化版 this.protocol == "https",用來檢查請求是否通過 TLS 發送。
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 和 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 時返回最佳匹配,否則返回 falsetype 的值可以是一個或者多個 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"
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 的值。
4.響應(Response)

Koa Response 對象是對 node 的 response 進一步抽象和封裝,提供了日常 HTTP 服務器開發中一些有用的功能。

API 簡介
res.header Response header 對象。
res.socket Request socket。
res.status 獲取 response status。不同於 node 在默認情況下 res.statusCode 為200,res.status 並沒有賦值。
res.statusString Response status 字符串。
res.status= 通過 數字狀態碼或者不區分大小寫的字符串來設置response status
100"continue"
101"switching protocols"
102"processing"
200"ok"
201"created"
202"accepted"
203"non-authoritative information"
204"no content"
205"reset content"
206"partial content"
207"multi-status"
300"multiple choices"
301"moved permanently"
302"moved temporarily"
303"see other"
304"not modified"
305"use proxy"
307"temporary redirect"
400"bad request"
401"unauthorized"
402"payment required"
403"forbidden"
404"not found"
405"method not allowed"
406"not acceptable"
407"proxy authentication required"
408"request time-out"
409"conflict"
410"gone"
411"length required"
412"precondition failed"
413"request entity too large"
414"request-uri too large"
415"unsupported media type"
416"requested range not satisfiable"
417"expectation failed"
418"i'm a teapot"
422"unprocessable entity"
423"locked"
424"failed dependency"
425"unordered collection"
426"upgrade required"
428"precondition required"
429"too many requests"
431"request header fields too large"
500"internal server error"
501"not implemented"
502"bad gateway"
503"service unavailable"
504"gateway time-out"
505"http version not supported"
506"variant also negotiates"
507"insufficient storage"
509"bandwidth limit exceeded"
510"not extended"
511"network authentication required"
注意:不用擔心記不住這些字符串,如果您設置錯誤,會有異常拋出,並列出該狀態碼表來幫助您進行更正。
 
res.length= 通過給定值設置 response Content-Length。
res.length 如果 Content-Length 作為數值存在,或者可以通過 res.body 來進行計算,則返回相應數值,否則返回 undefined。
res.body 獲得 response body。
res.body=

設置 response body 為如下值: 

string written
Buffer written
Stream piped
Object json-stringified
null no content response
如果 res.status 沒有賦值,Koa會自動設置為 200 或 204。
String Content-Type 默認為 text/html 或者 text/plain,兩種默認 charset 均為 utf-8。 Content-Length 同時會被設置。
Buffer Content-Type 默認為 application/octet-stream,Content-Length同時被設置。
Stream Content-Type 默認為 application/octet-stream。
Object Content-Type 默認為 application/json。
res.get(field) 獲取 response header 中字段值,field 不區分大小寫。
var etag =this.get('ETag');
res.set(field, value) 設置 response header 字段 field 的值為 value。
this.set('Cache-Control','no-cache');
res.set(fields) 使用對象同時設置 response header 中多個字段的值。
this.set({
'Etag':'1234',
'Last-Modified': date
});
res.remove(field) 移除 response header 中字段 filed。
res.type 獲取 response Content-Type,不包含像 "charset" 這樣的參數。
var ct =this.type;
// => "image/png"
res.type=

通過 mime 類型的字符串或者文件擴展名設置 response Content-Type

 

this.type ='text/plain; charset=utf-8';
this.type ='image/png';
this.type ='.png';
this.type ='png';


注意:當可以根據 res.type 確定一個合適的 charset 時,charset 會自動被賦值。 比如 res.type = 'html' 時,charset 將會默認設置為 "utf-8"。然而當完整定義為 res.type = 'text/html'時,charset 不會自動設置。

 
res.redirect(url, [alt]) 執行 [302] 重定向到對應 url。
字符串 "back" 是一個特殊參數,其提供了 Referrer 支持。當沒有Referrer時,使用 alt 或者 / 代替。
this.redirect('back');
this.redirect('back','/index.html');
this.redirect('/login');
this.redirect('http://google.com');
如果想要修改默認的 [302] 狀態,直接在重定向之前或者之后執行即可。如果要修改 body,需要在重定向之前執行。
this.status =301;
this.redirect('/cart');
this.body ='Redirecting to shopping cart';
res.attachment([filename]) 設置 "attachment" 的 Content-Disposition,用於給客戶端發送信號來提示下載。filename 為可選參數,用於指定下載文件名。
res.headerSent 檢查 response header 是否已經發送,用於在發生錯誤時檢查客戶端是否被通知。
res.lastModified 如果存在 Last-Modified,則以 Date 的形式返回。
res.lastModified= 以 UTC 格式設置 Last-Modified。您可以使用 Date 或 date 字符串來進行設置。
this.response.lastModified =newDate()
res.etag= 設置 包含 "s 的 ETag。注意沒有對應的 res.etag 來獲取其值。
this.response.etag = crypto.createHash('md5').update(this.body).digest('hex');
res.append(field, val) 在 header 的 field 后面 追加 val。
res.vary(field) 相當於執行res.append('Vary', field)。


免責聲明!

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



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