基于 Node.js 平臺(tái)的下一代 web 開(kāi)發(fā)框架,包含 Koa 的 API 參考列表和一些示例
Koa 需要 node v7.6.0 或更高版本來(lái)支持ES2015、異步方法,你可以安裝自己支持的 node 版本
安裝依賴(lài)
$ mkdir myapp # 創(chuàng)建目錄
$ cd myapp # 進(jìn)入目錄
$ nvm install 7
$ npm init -y # 初始化一個(gè)配置
$ npm install koa # 安裝依賴(lài)
入口文件 index.js 添加代碼:
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
使用以下命令運(yùn)行應(yīng)用程序
$ node index.js
const Koa = require('koa');
const app = new Koa();
// X-Response-Time x 響應(yīng)時(shí)間
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// 記錄器 logger
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(
`${ctx.method} ${ctx.url} - ${ms}`
);
});
// 響應(yīng) response
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
| :- | :- |
|---|---|
app.env | 默認(rèn)為 NODE_ENV 或 development |
app.keys | 簽名 cookie 密鑰數(shù)組 |
app.proxy | 何時(shí)信任真正的代理頭字段 |
app.subdomainOffset | 要忽略的 .subdomains 的偏移量,默認(rèn)為 2 |
app.proxyIpHeader | 代理 ip 頭,默認(rèn)為 X-Forwarded-For |
app.maxIpsCount | 從代理 ip 頭讀取的最大 ips 數(shù),默認(rèn)為 0(表示無(wú)窮大) |
app.on('error', (err, ctx) => {
log.error('server error', err, ctx)
});
默認(rèn)情況下 Koa 會(huì)將所有錯(cuò)誤信息輸出到 stderr, 除非 app.silent 是 true。當(dāng) err.status 是 404 或者 err.expose 時(shí),默認(rèn)錯(cuò)誤處理程序也不會(huì)輸出錯(cuò)誤
app.use(async ctx => {
ctx; // 這是上下文 Context
ctx.request; // 這是 koa Request
ctx.response; // 這是 koa Response
});
const Koa = require('koa');
const app = new Koa();
app.listen(3000);
app.listen(...) 實(shí)際上是以下代碼的語(yǔ)法糖:
const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
這意味著您可以同時(shí)支持 HTTPS 和 HTTPS,或者在 多個(gè)端口 監(jiān)聽(tīng)同一個(gè)應(yīng)用
const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);
ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });
this.throw('name required', 400) 等價(jià)于
const err = new Error('name required');
err.status = 400;
err.expose = true;
throw err;
ctx.assert(
ctx.state.user,
401,
'User not found. Please login!'
);
| :- | :- |
|---|---|
ctx.req | Node 的 request 對(duì)象 |
ctx.res | Node 的 response 對(duì)象 |
ctx.request | Koa 的 Request 對(duì)象 |
ctx.response | Koa 的 Response 對(duì)象 |
ctx.state | 推薦的命名空間,用于通過(guò)中間件傳遞信息到前端視圖 |
ctx.app | 應(yīng)用實(shí)例引用 |
ctx.app.emit | 發(fā)出由第一個(gè)參數(shù)定義的類(lèi)型的事件 |
ctx.cookies.get(name, [options]) | 獲得 cookie 中名為 name 的值 |
ctx.cookies.set(name, value, [options]) | 設(shè)置 cookie 中名為 name 的值 |
ctx.throw([status], [msg], [properties]) | 拋出包含 .status 屬性的錯(cuò)誤,默認(rèn)為 500 |
ctx.assert(value, [status], [msg], [properties]) | 當(dāng) !value 時(shí), Helper 方法拋出一個(gè)類(lèi)似 .throw() 的錯(cuò)誤 |
ctx.respond | 避免使用 Koa 的內(nèi)置響應(yīng)處理功能,您可以直接賦值 this.repond = false |
| :- | :- |
|---|---|
maxAge | 表示從Date開(kāi)始的毫秒數(shù) now() 到期。 |
expires | 一個(gè) Date 對(duì)象,指示 cookie 的到期日期(默認(rèn)情況下在會(huì)話(huà)結(jié)束時(shí)到期) |
path | 表示 cookie 路徑的字符串(默認(rèn)為/) |
domain | 表示 cookie 的域的字符串(無(wú)默認(rèn)值) |
secure | 一個(gè)布爾值,指示 cookie 是否只通過(guò)HTTPS發(fā)送(HTTP默認(rèn)為false,HTTPS默認(rèn)為true)。閱讀有關(guān)此選項(xiàng)的更多信息 |
httpOnly | 一個(gè)布爾值,指示cookie是否只通過(guò)HTTP(S)發(fā)送,而不可用于客戶(hù)端 JavaScript(默認(rèn)為true) |
sameSite | 一個(gè)布爾值或字符串,指示cookie是否為“同一站點(diǎn)”cookie(默認(rèn)為false)。這可以設(shè)置為“strict”、“l(fā)ax”、“none”或true(映射為“strect”) |
signed | 一個(gè)布爾值,指示是否對(duì)cookie進(jìn)行簽名(默認(rèn)為false)。如果這是真的,還將發(fā)送另一個(gè)附加了.sig后綴的同名cookie,其中一個(gè)27字節(jié)的url安全base64 SHA1值表示cookie name=cookie值相對(duì)于第一個(gè)Keygrip鍵的哈希值。此簽名密鑰用于在下次收到cookie時(shí)檢測(cè)篡改 |
overwrite | 一個(gè)布爾值,指示是否覆蓋以前設(shè)置的同名 cookie(默認(rèn)為false)。如果為true,則在設(shè)置此Cookie時(shí),將從set-Cookie標(biāo)頭中篩選出在同一請(qǐng)求期間設(shè)置的具有相同名稱(chēng)的所有Cookie(無(wú)論路徑或域如何) |
| :- | :- |
|---|---|
request.header | 請(qǐng)求頭對(duì)象 |
request.header= | 設(shè)置請(qǐng)求頭對(duì)象 |
request.headers | 請(qǐng)求頭對(duì)象。等價(jià)于 request.header. |
request.headers= | 設(shè)置請(qǐng)求頭對(duì)象。 等價(jià)于request.header=. |
request.method | 請(qǐng)求方法 |
request.method= | 設(shè)置請(qǐng)求方法, 在實(shí)現(xiàn)中間件時(shí)非常有用,比如 methodOverride() |
request.length | 以數(shù)字的形式返回 request 的內(nèi)容長(zhǎng)度(Content-Length),或者返回 undefined。 |
request.url | 獲得請(qǐng)求url地址. |
request.url= | 設(shè)置請(qǐng)求地址,用于重寫(xiě)url地址時(shí) |
request.originalUrl | 獲取請(qǐng)求原始地址 |
request.origin | 獲取URL原始地址, 包含 protocol 和 host |
request.href | 獲取完整的請(qǐng)求URL, 包含 protocol, host 和 url |
request.path | 獲取請(qǐng)求路徑名 |
request.path= | 設(shè)置請(qǐng)求路徑名并保留當(dāng)前查詢(xún)字符串 |
request.querystring | 獲取查詢(xún)參數(shù)字符串(url中?后面的部分),不包含? |
request.querystring= | 設(shè)置原始查詢(xún)字符串 |
request.search | 獲取查詢(xún)參數(shù)字符串,包含? |
request.search= | 設(shè)置原始查詢(xún)字符串 |
request.host | 獲取 host (hostname:port)。 當(dāng) app.proxy 設(shè)置為 true 時(shí),支持 X-Forwarded-Host |
request.hostname | 獲取 hostname。當(dāng) app.proxy 設(shè)置為 true 時(shí),支持 X-Forwarded-Host。 |
request.URL | 獲取 WHATWG 解析的對(duì)象. |
request.type | 獲取請(qǐng)求 Content-Type,不包含像 "charset" 這樣的參數(shù)。 |
request.charset | 獲取請(qǐng)求 charset,沒(méi)有則返回 undefined |
request.query | 將查詢(xún)參數(shù)字符串進(jìn)行解析并以對(duì)象的形式返回,如果沒(méi)有查詢(xún)參數(shù)字字符串則返回一個(gè)空對(duì)象 |
request.query= | 根據(jù)給定的對(duì)象設(shè)置查詢(xún)參數(shù)字符串 |
request.fresh | 檢查請(qǐng)求緩存是否 "fresh"(內(nèi)容沒(méi)有發(fā)生變化) |
request.stale | 與 req.fresh 相反 |
request.protocol | 返回請(qǐng)求協(xié)議,"https" 或者 "http" |
request.secure | 簡(jiǎn)化版 this.protocol == "https",用來(lái)檢查請(qǐng)求是否通過(guò) TLS 發(fā)送 |
request.ip | 請(qǐng)求遠(yuǎn)程地址,當(dāng) app.proxy 設(shè)置為 true 時(shí),支持 X-Forwarded-Host |
request.ips | 當(dāng) X-Forwarded-For 存在并且 app.proxy 有效,將會(huì)返回一個(gè)有序(從 upstream 到 downstream)ip 數(shù)組 |
request.subdomains | 以數(shù)組形式返回子域名 |
request.is(types...) | 檢查請(qǐng)求所包含的 "Content-Type" 是否為給定的 type 值 |
request.accepts(types) | 檢查給定的類(lèi)型 types(s) 是否可被接受,當(dāng)為 true 時(shí)返回最佳匹配,否則返回 false |
request.acceptsEncodings(encodings) | 檢查 encodings 是否可以被接受,當(dāng)為 true 時(shí)返回最佳匹配,否則返回 false |
request.acceptsCharsets(charsets) | 檢查 charsets 是否可以被接受,如果為 true 則返回最佳匹配,否則返回 false |
request.acceptsLanguages(langs) | 檢查 langs 是否可以被接受,如果為 true 則返回最佳匹配,否則返回 false |
request.idempotent | 檢查請(qǐng)求是否為冪等(idempotent) |
request.socket | 返回請(qǐng)求的socket |
request.get(field) | 返回請(qǐng)求頭 |
| :- | :- |
|---|---|
response.header | Response header 對(duì)象 |
response.headers | Response header 對(duì)象。等價(jià)于 response.header. |
response.socket | Request socket. |
response.status | 獲取響應(yīng)狀態(tài)。 默認(rèn)情況下,response.status設(shè)置為404,而不像node's res.statusCode默認(rèn)為200。 |
response.status= | 通過(guò)數(shù)字設(shè)置響應(yīng)狀態(tài) |
response.message | 獲取響應(yīng)狀態(tài)消息。默認(rèn)情況下, response.message關(guān)聯(lián)response.status。 |
response.message= | 將響應(yīng)狀態(tài)消息設(shè)置為給定值。 |
response.length= | 將響應(yīng)Content-Length設(shè)置為給定值。 |
response.length | 如果 Content-Length 作為數(shù)值存在,或者可以通過(guò) ctx.body 來(lái)進(jìn)行計(jì)算,則返回相應(yīng)數(shù)值,否則返回 undefined。 |
response.body | 獲取響應(yīng)體。 |
response.body= | 設(shè)置響應(yīng)體為如 string,Buffer,Stream,Object|Array,null |
response.get(field) | 獲取 response header 中字段值,field 不區(qū)分大小寫(xiě) |
response.set(field, value) | 設(shè)置 response header 字段 field 的值為 value |
response.append(field, value) | 添加額外的字段field 的值為 val |
response.set(fields) | 使用對(duì)象同時(shí)設(shè)置 response header 中多個(gè)字段的值 |
response.remove(field) | 移除 response header 中字段 filed |
response.type | 獲取 response Content-Type,不包含像"charset"這樣的參數(shù) |
response.type= | 通過(guò) mime 類(lèi)型的字符串或者文件擴(kuò)展名設(shè)置 response Content-Type |
response.is(types...) | 跟 ctx.request.is() 非常類(lèi)似。用來(lái)檢查響應(yīng)類(lèi)型是否是所提供的類(lèi)型之一 |
response.redirect(url, [alt]) | 執(zhí)行 [302] 重定向到對(duì)應(yīng) url |
response.attachment([filename]) | 設(shè)置 "attachment" 的 Content-Disposition,用于給客戶(hù)端發(fā)送信號(hào)來(lái)提示下載 |
response.headerSent | 檢查 response header 是否已經(jīng)發(fā)送,用于在發(fā)生錯(cuò)誤時(shí)檢查客戶(hù)端是否被通知。 |
response.lastModified | 如果存在 Last-Modified,則以 Date 的形式返回。 |
response.lastModified= | 以 UTC 格式設(shè)置 Last-Modified。您可以使用 Date 或 date 字符串來(lái)進(jìn)行設(shè)置。 |
response.etag= | 設(shè)置 包含 "s 的 ETag |
response.vary(field) | 不同于field. |
response.flushHeaders() | 刷新任何設(shè)置的響應(yīng)頭,并開(kāi)始響應(yīng)體 |
以下訪問(wèn)器和別名與 Request 等價(jià):
ctx.headerctx.headersctx.methodctx.method=ctx.urlctx.url=ctx.originalUrlctx.originctx.hrefctx.pathctx.path=ctx.queryctx.query=ctx.querystringctx.querystring=ctx.hostctx.hostnamectx.freshctx.stalectx.socketctx.protocolctx.securectx.ipctx.ipsctx.subdomainsctx.is()ctx.accepts()ctx.acceptsEncodings()ctx.acceptsCharsets()ctx.acceptsLanguages()ctx.get()以下訪問(wèn)器和別名與 Response 等價(jià):
ctx.bodyctx.body=ctx.statusctx.status=ctx.messagectx.message=ctx.length=ctx.lengthctx.type=ctx.typectx.headerSentctx.redirect()ctx.attachment()ctx.set()ctx.append()ctx.remove()ctx.lastModified=ctx.etag=// freshness 檢查需要狀態(tài) 20x 或 304
ctx.status = 200;
ctx.set('ETag', '123');
// 緩存正常
if (ctx.fresh) {
ctx.status = 304;
return;
}
// 緩存已過(guò)時(shí)
// 獲取新數(shù)據(jù)
ctx.body = await db.find('something');
// Content-Type: text/html; charset=utf-8
ctx.is('html'); // => 'html'
ctx.is('text/html'); // => 'text/html'
ctx.is('text/*', 'text/html');
// => 'text/html'
// 當(dāng) Content-Type 為 application/json 時(shí)
ctx.is('json', 'urlencoded'); // => 'json'
ctx.is('application/json');
// => 'application/json'
ctx.is('html', 'application/*');
// => 'application/json'
ctx.is('html'); // => false
// 接受: text/*, application/json
ctx.accepts('html');
// => "html"
ctx.accepts('text/html');
// => "text/html"
ctx.accepts('json', 'text');
// => "json"
ctx.accepts('application/json');
// => "application/json"
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"
ctx.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"
檢查 charsets 是否可以被接受,如果為 true 則返回最佳匹配, 否則返回 false
ctx.set({
'Etag': '1234',
'Last-Modified': date
});
使用對(duì)象同時(shí)設(shè)置 response header 中多個(gè)字段的值
const ct = ctx.type;
// => "image/png"
獲取 response Content-Type,不包含像"charset"這樣的參數(shù)
感谢您访问我们的网站,您可能还对以下资源感兴趣:
国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片