此係列文章的應用示例已發佈於 GitHub: koa-docs-Zh-CN. 能夠 Fork 幫助改進或 Star 關注更新. 歡迎 Star.html
Koa Context 將 node 的 request
和 response
對象封裝到單個對象中,爲編寫 Web 應用程序和 API 提供了許多有用的方法。
這些操做在 HTTP 服務器開發中頻繁使用,它們被添加到此級別而不是更高級別的框架,這將強制中間件從新實現此通用功能。前端
每一個 請求都將建立一個 Context
,並在中間件中做爲接收器引用,或者 ctx
標識符,如如下代碼片斷所示:node
app.use(async ctx => { ctx; // 這是 Context ctx.request; // 這是 koa Request ctx.response; // 這是 koa Response });
爲方便起見許多上下文的訪問器和方法直接委託給它們的 ctx.request
或 ctx.response
,否則的話它們是相同的。
例如 ctx.type
和 ctx.length
委託給 response
對象,ctx.path
和 ctx.method
委託給 request
。git
Context
具體方法和訪問器.github
Node 的 request
對象.segmentfault
Node 的 response
對象.api
繞過 Koa 的 response 處理是 __不被支持的__. 應避免使用如下 node 屬性:安全
res.statusCode
res.writeHead()
res.write()
res.end()
koa 的 Request
對象.服務器
koa 的 Response
對象.cookie
推薦的命名空間,用於經過中間件傳遞信息和你的前端視圖。
ctx.state.user = await User.find(id);
應用程序實例引用
經過 options
獲取 cookie name
:
signed
所請求的cookie應該被簽名koa 使用 cookies 模塊,其中只需傳遞參數。
經過 options
設置 cookie name
的 value
:
maxAge
一個數字表示從 Date.now() 獲得的毫秒數signed
cookie 簽名值expires
cookie 過時的 Date
path
cookie 路徑, 默認是'/'
domain
cookie 域名secure
安全 cookiehttpOnly
服務器可訪問 cookie, 默認是 true overwrite
一個布爾值,表示是否覆蓋之前設置的同名的 cookie (默認是 __false__). 若是是 true, 在同一個請求中設置相同名稱的全部 Cookie(無論路徑或域)是否在設置此Cookie 時從 Set-Cookie 標頭中過濾掉。koa 使用傳遞簡單參數的 cookies 模塊。
Helper 方法拋出一個 .status
屬性默認爲 500
的錯誤,這將容許 Koa 作出適當地響應。
容許如下組合:
ctx.throw(400); ctx.throw(400, 'name required'); ctx.throw(400, 'name required', { user: user });
例如 ctx.throw(400, 'name required')
等效於:
const err = new Error('name required'); err.status = 400; err.expose = true; throw err;
請注意,這些是用戶級錯誤,並用 err.expose
標記,這意味着消息適用於客戶端響應,這一般不是錯誤消息的內容,由於您不想泄漏故障詳細信息。
你能夠根據須要將 properties
對象傳遞到錯誤中,對於裝載上傳給請求者的機器友好的錯誤是有用的。這用於修飾其人機友好型錯誤並向上遊的請求者報告很是有用。
ctx.throw(401, 'access_denied', { user: user });
koa 使用 http-errors 來建立錯誤。
當 !value
時,Helper 方法拋出相似於 .throw()
的錯誤。這與 node 的 assert() 方法相似.
ctx.assert(ctx.state.user, 401, 'User not found. Please login!');
koa 使用 http-assert 做爲斷言。
爲了繞過 Koa 的內置 response 處理,你能夠顯式設置 ctx.respond = false;
。 若是您想要寫入原始的 res
對象而不是讓 Koa 處理你的 response,請使用此參數。
請注意,Koa 不 支持使用此功能。這可能會破壞 Koa 中間件和 Koa 自己的預期功能。使用這個屬性被認爲是一個 hack,只是便於那些但願在 Koa 中使用傳統的 fn(req, res)
功能和中間件的人。
如下訪問器和 Request 別名等效:
ctx.header
ctx.headers
ctx.method
ctx.method=
ctx.url
ctx.url=
ctx.originalUrl
ctx.origin
ctx.href
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 別名等效:
ctx.body
ctx.body=
ctx.status
ctx.status=
ctx.message
ctx.message=
ctx.length=
ctx.length
ctx.type=
ctx.type
ctx.headerSent
ctx.redirect()
ctx.attachment()
ctx.set()
ctx.append()
ctx.remove()
ctx.lastModified=
ctx.etag=
若是這篇文章對您有幫助, 感謝 下方點贊 或 Star GitHub: koa-docs-Zh-CN 支持, 謝謝.