Koa v2.x 中文文檔 上下文(Context)

上下文(Context)

此係列文章的應用示例已發佈於 GitHub: koa-docs-Zh-CN. 能夠 Fork 幫助改進或 Star 關注更新. 歡迎 Star.html

Koa Context 將 node 的 requestresponse 對象封裝到單個對象中,爲編寫 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.typectx.length 委託給 response 對象,ctx.pathctx.method 委託給 requestgit

API

Context 具體方法和訪問器.github

ctx.req

Node 的 request 對象.segmentfault

ctx.res

Node 的 response 對象.api

繞過 Koa 的 response 處理是 __不被支持的__. 應避免使用如下 node 屬性:安全

  • res.statusCode
  • res.writeHead()
  • res.write()
  • res.end()

ctx.request

koa 的 Request 對象.服務器

ctx.response

koa 的 Response 對象.cookie

ctx.state

推薦的命名空間,用於經過中間件傳遞信息和你的前端視圖。

ctx.state.user = await User.find(id);

ctx.app

應用程序實例引用

ctx.cookies.get(name, [options])

經過 options 獲取 cookie name:

  • signed 所請求的cookie應該被簽名

koa 使用 cookies 模塊,其中只需傳遞參數。

ctx.cookies.set(name, value, [options])

經過 options 設置 cookie namevalue :

  • maxAge 一個數字表示從 Date.now() 獲得的毫秒數
  • signed cookie 簽名值
  • expires cookie 過時的 Date
  • path cookie 路徑, 默認是'/'
  • domain cookie 域名
  • secure 安全 cookie
  • httpOnly 服務器可訪問 cookie, 默認是 true
  • overwrite 一個布爾值,表示是否覆蓋之前設置的同名的 cookie (默認是 __false__). 若是是 true, 在同一個請求中設置相同名稱的全部 Cookie(無論路徑或域)是否在設置此Cookie 時從 Set-Cookie 標頭中過濾掉。

koa 使用傳遞簡單參數的 cookies 模塊。

ctx.throw([status], [msg], [properties])

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 來建立錯誤。

ctx.assert(value, [status], [msg], [properties])

!value 時,Helper 方法拋出相似於 .throw() 的錯誤。這與 node 的 assert() 方法相似.

ctx.assert(ctx.state.user, 401, 'User not found. Please login!');

koa 使用 http-assert 做爲斷言。

ctx.respond

爲了繞過 Koa 的內置 response 處理,你能夠顯式設置 ctx.respond = false;。 若是您想要寫入原始的 res 對象而不是讓 Koa 處理你的 response,請使用此參數。

請注意,Koa 支持使用此功能。這可能會破壞 Koa 中間件和 Koa 自己的預期功能。使用這個屬性被認爲是一個 hack,只是便於那些但願在 Koa 中使用傳統的 fn(req, res) 功能和中間件的人。

Request 別名

如下訪問器和 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 別名

如下訪問器和 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 支持, 謝謝.

相關文章
相關標籤/搜索