Koa 響應(yīng)(Response)

2020-02-07 15:24 更新

響應(yīng)(Response)

Koa Response 對象是在 node 的 vanilla 響應(yīng)對象之上的抽象,提供了諸多對 HTTP 服務(wù)器開發(fā)有用的功能。

API

response.header

響應(yīng)標(biāo)頭對象。

response.headers

響應(yīng)標(biāo)頭對象。別名是 response.header。

response.socket

響應(yīng)套接字。 作為 request.socket 指向 net.Socket 實(shí)例。

response.status

獲取響應(yīng)狀態(tài)。默認(rèn)情況下,response.status 設(shè)置為 404 而不是像 node 的 res.statusCode 那樣默認(rèn)為 200。

response.status=

通過數(shù)字代碼設(shè)置響應(yīng)狀態(tài):

  • 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"

注意: 不用太在意記住這些字符串, 如果你寫錯(cuò)了,可以查閱這個(gè)列表隨時(shí)更正.

response.message

獲取響應(yīng)的狀態(tài)消息. 默認(rèn)情況下, response.message 與 response.status 關(guān)聯(lián).

response.message=

將響應(yīng)的狀態(tài)消息設(shè)置為給定值。

response.length=

將響應(yīng)的 Content-Length 設(shè)置為給定值。

response.length

以數(shù)字返回響應(yīng)的 Content-Length,或者從ctx.body推導(dǎo)出來,或者undefined。

response.body

獲取響應(yīng)主體。

response.body=

將響應(yīng)體設(shè)置為以下之一:

  • string 寫入
  • Buffer 寫入
  • Stream 管道
  • Object || Array JSON-字符串化
  • null 無內(nèi)容響應(yīng)

如果 response.status 未被設(shè)置, Koa 將會(huì)自動(dòng)設(shè)置狀態(tài)為 200 或 204。

Koa 沒有防范作為響應(yīng)體的所有內(nèi)容 - 函數(shù)沒有有意義地序列化,返回布爾值可能會(huì)根據(jù)您的應(yīng)用程序而有意義。并且當(dāng)錯(cuò)誤生效時(shí),它可能無法正常工作 錯(cuò)誤的屬性無法枚舉。 我們建議在您的應(yīng)用中添加中間件,以確定每個(gè)應(yīng)用的正文類型。 示例中間件可能是:

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

  ctx.assert.equal('object', typeof ctx, 500, '某些開發(fā)錯(cuò)誤')
})

String

Content-Type 默認(rèn)為 text/html 或 text/plain, 同時(shí)默認(rèn)字符集是 utf-8。Content-Length 字段也是如此。

Buffer

Content-Type 默認(rèn)為 application/octet-stream, 并且 Content-Length 字段也是如此。

Stream

Content-Type 默認(rèn)為 application/octet-stream。

每當(dāng)流被設(shè)置為響應(yīng)主體時(shí),.onerror 作為偵聽器自動(dòng)添加到 error 事件中以捕獲任何錯(cuò)誤。此外,每當(dāng)請求關(guān)閉(甚至過早)時(shí),流都將被銷毀。如果你不想要這兩個(gè)功能,請勿直接將流設(shè)為主體。例如,當(dāng)將主體設(shè)置為代理中的 HTTP 流時(shí),你可能不想要這樣做,因?yàn)樗鼤?huì)破壞底層連接。

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

以下是流錯(cuò)誤處理的示例,而不會(huì)自動(dòng)破壞流:

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

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

Object

Content-Type 默認(rèn)為 application/json. 這包括普通的對象 { foo: 'bar' } 和數(shù)組 ['foo', 'bar']。

response.get(field)

不區(qū)分大小寫獲取響應(yīng)標(biāo)頭字段值 field。

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

response.has(field)

如果當(dāng)前在傳出標(biāo)頭中設(shè)置了由名稱標(biāo)識(shí)的標(biāo)頭,則返回 true. 標(biāo)頭名稱匹配不區(qū)分大小寫.

const rateLimited = ctx.response.has('X-RateLimit-Limit');

response.set(field, value)

設(shè)置響應(yīng)標(biāo)頭 field 到 value:

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

response.append(field, value)

用值 val 附加額外的標(biāo)頭 field。

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

response.set(fields)

用一個(gè)對象設(shè)置多個(gè)響應(yīng)標(biāo)頭fields:

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

這將委托給 setHeader ,它通過指定的鍵設(shè)置或更新標(biāo)頭,并且不重置整個(gè)標(biāo)頭。

response.remove(field)

刪除標(biāo)頭 field。

response.type

獲取響應(yīng) Content-Type 不含參數(shù) "charset"。

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

response.type=

設(shè)置響應(yīng) Content-Type 通過 mime 字符串或文件擴(kuò)展名。

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

注意: 在適當(dāng)?shù)那闆r下為你選擇 charset, 比如 response.type = 'html' 將默認(rèn)是 "utf-8". 如果你想覆蓋 charset, 使用 ctx.set('Content-Type', 'text/html') 將響應(yīng)頭字段設(shè)置為直接值。

response.is(types...)

非常類似 ctx.request.is(). 檢查響應(yīng)類型是否是所提供的類型之一。這對于創(chuàng)建操縱響應(yīng)的中間件特別有用。

例如, 這是一個(gè)中間件,可以削減除流之外的所有HTML響應(yīng)。

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])

執(zhí)行 [302] 重定向到 url.

字符串 “back” 是特別提供Referrer支持的,當(dāng)Referrer不存在時(shí),使用 alt 或“/”。

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

要更改 “302” 的默認(rèn)狀態(tài),只需在該調(diào)用之前或之后分配狀態(tài)。要變更主體請?jiān)诖苏{(diào)用之后:

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

response.attachment([filename], [options])

將 Content-Disposition 設(shè)置為 “附件” 以指示客戶端提示下載。(可選)指定下載的 filename 和部分 參數(shù)

response.headerSent

檢查是否已經(jīng)發(fā)送了一個(gè)響應(yīng)頭。 用于查看客戶端是否可能會(huì)收到錯(cuò)誤通知。

response.lastModified

將 Last-Modified 標(biāo)頭返回為 Date, 如果存在。

response.lastModified=

將 Last-Modified 標(biāo)頭設(shè)置為適當(dāng)?shù)?UTC 字符串。您可以將其設(shè)置為 Date 或日期字符串。

ctx.response.lastModified = new Date();

response.etag=

設(shè)置包含 " 包裹的 ETag 響應(yīng), 請注意,沒有相應(yīng)的 response.etag getter。

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

response.vary(field)

在 field 上變化。

response.flushHeaders()

刷新任何設(shè)置的標(biāo)頭,并開始主體。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)