Koa v2.x 中文文檔 響應(Response)

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

響應(Response)

Koa Response 對象是在 node 的 vanilla 響應對象之上的抽象,提供了諸多對 HTTP 服務器開發有用的功能。node

API

response.header

響應標頭對象。git

response.headers

響應標頭對象。別名是 response.headergithub

response.socket

請求套接字。json

response.status

獲取響應狀態。默認狀況下,response.status 設置爲 404 而不是像 node 的 res.statusCode 那樣默認爲 200數組

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"
  • 208 "already reported"
  • 226 "im used"
  • 300 "multiple choices"
  • 301 "moved permanently"
  • 302 "found"
  • 303 "see other"
  • 304 "not modified"
  • 305 "use proxy"
  • 307 "temporary redirect"
  • 308 "permanent 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 timeout"
  • 409 "conflict"
  • 410 "gone"
  • 411 "length required"
  • 412 "precondition failed"
  • 413 "payload too large"
  • 414 "uri too long"
  • 415 "unsupported media type"
  • 416 "range not satisfiable"
  • 417 "expectation failed"
  • 418 "I'm a teapot"
  • 422 "unprocessable entity"
  • 423 "locked"
  • 424 "failed dependency"
  • 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 timeout"
  • 505 "http version not supported"
  • 506 "variant also negotiates"
  • 507 "insufficient storage"
  • 508 "loop detected"
  • 510 "not extended"
  • 511 "network authentication required"

__注意__: 不用太在乎記住這些字符串, 若是你寫錯了,能夠查閱這個列表隨時更正.app

response.message

獲取響應的狀態消息. 默認狀況下, response.messageresponse.status 關聯.koa

response.message=

將響應的狀態消息設置爲給定值。socket

response.length=

將響應的 Content-Length 設置爲給定值。

response.length

以數字返回響應的 Content-Length,或者從ctx.body推導出來,或者undefined

response.body

獲取響應主體。

response.body=

將響應體設置爲如下之一:

  • string 寫入
  • Buffer 寫入
  • Stream 管道
  • Object || Array JSON-字符串化
  • null 無內容響應

若是 response.status 未被設置, Koa 將會自動設置狀態爲 200204

String

Content-Type 默認爲 text/htmltext/plain, 同時默認字符集是 utf-8。Content-Length 字段也是如此。

Buffer

Content-Type 默認爲 application/octet-stream, 而且 Content-Length 字段也是如此。

Stream

Content-Type 默認爲 application/octet-stream

每當流被設置爲響應主體時,.onerror 做爲偵聽器自動添加到 error 事件中以捕獲任何錯誤。此外,每當請求關閉(甚至過早)時,流都將被銷燬。若是你不想要這兩個功能,請勿直接將流設爲主體。例如,當將主體設置爲代理中的 HTTP 流時,你可能不想要這樣作,由於它會破壞底層鏈接。

參閱: https://github.com/koajs/koa/... 獲取更多信息。

如下是流錯誤處理的示例,而不會自動破壞流:

const PassThrough = require('stream').PassThrough;

app.use(async ctx => {
  ctx.body = someHTTPStream.on('error', ctx.onerror).pipe(PassThrough());
});

Object

Content-Type 默認爲 application/json. 這包括普通的對象 { foo: 'bar' } 和數組 ['foo', 'bar']

response.get(field)

不區分大小寫獲取響應標頭字段值 field

const etag = ctx.response.get('ETag');

response.set(field, value)

設置響應標頭 fieldvalue:

ctx.set('Cache-Control', 'no-cache');

response.append(field, value)

用值 val 附加額外的標頭 field

ctx.append('Link', '<http://127.0.0.1/>');

response.set(fields)

用一個對象設置多個響應標頭fields:

ctx.set({
  'Etag': '1234',
  'Last-Modified': date
});

response.remove(field)

刪除標頭 field

response.type

獲取響應 Content-Type 不含參數 "charset"。

const ct = ctx.type;
// => "image/png"

response.type=

設置響應 Content-Type 經過 mime 字符串或文件擴展名。

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

注意: 在適當的狀況下爲你選擇 charset, 好比 response.type = 'html' 將默認是 "utf-8". 若是你想覆蓋 charset, 使用 ctx.set('Content-Type', 'text/html') 將響應頭字段設置爲直接值。

response.is(types...)

很是相似 ctx.request.is(). 檢查響應類型是不是所提供的類型之一。這對於建立操縱響應的中間件特別有用。

例如, 這是一箇中間件,能夠削減除流以外的全部HTML響應。

const minify = require('html-minifier');

app.use(async (ctx, next) => {
  await next();

  if (!ctx.response.is('html')) return;

  let body = ctx.body;
  if (!body || body.pipe) return;

  if (Buffer.isBuffer(body)) body = body.toString();
  ctx.body = minify(body);
});

response.redirect(url, [alt])

執行 [302] 重定向到 url.

字符串 「back」 是特別提供Referrer支持的,當Referrer不存在時,使用 alt 或「/」。

ctx.redirect('back');
ctx.redirect('back', '/index.html');
ctx.redirect('/login');
ctx.redirect('http://google.com');

要更改 「302」 的默認狀態,只需在該調用以前或以後分配狀態。要變動主體請在此調用以後:

ctx.status = 301;
ctx.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';

response.attachment([filename])

Content-Disposition 設置爲 「附件」 以指示客戶端提示下載。(可選)指定下載的 filename

response.headerSent

檢查是否已經發送了一個響應頭。 用於查看客戶端是否可能會收到錯誤通知。

response.lastModified

Last-Modified 標頭返回爲 Date, 若是存在。

response.lastModified=

Last-Modified 標頭設置爲適當的 UTC 字符串。您能夠將其設置爲 Date 或日期字符串。

ctx.response.lastModified = new Date();

response.etag=

設置包含 " 包裹的 ETag 響應,
請注意,沒有相應的 response.etag getter。

ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');

response.vary(field)

field 上變化。

response.flushHeaders()

刷新任何設置的標頭,並開始主體。

若是這篇文章對您有幫助, 感謝 下方點贊 或 Star GitHub: koa-docs-Zh-CN 支持, 謝謝.

相關文章
相關標籤/搜索