KOA 學習(四)

響應(Response)

Koa Response 對象是對 node 的 response 進一步抽象和封裝,提供了平常 HTTP 服務器開發中一些有用的功能。html

response.header

Response header 對象。node

response.socket

response.status

獲取 response status。不一樣於 node 在默認狀況下 res.statusCode 爲200,res.status 並無賦值。json

response.status=

經過 數字狀態碼或者不區分大小寫的字符串來設置response status:服務器

response.message

Get response status message. By default, response.message is associated with response.status.app

response.message=

Set response status message to the given value.socket

response.length=

經過給定值設置 response Content-Length。ui

response.length

若是 Content-Length 做爲數值存在,或者能夠經過 res.body 來進行計算,則返回相應數值,不然返回 undefinedthis

response.body

得到 response body。google

response.body=

設置 response body 爲以下值:url

  • string written
  • Buffer written
  • Stream piped
  • Object json-stringified
  • null no content response

若是 res.status 沒有賦值,Koa會自動設置爲 200 或 204

String

Content-Type 默認爲 text/html 或者 text/plain,兩種默認 charset 均爲 utf-8。 Content-Length 同時會被設置。

Buffer

Content-Type 默認爲 application/octet-stream,Content-Length同時被設置。

Stream

Content-Type 默認爲 application/octet-stream。

Object

Content-Type 默認爲 application/json。

response.get(field)

獲取 response header 中字段值,field 不區分大小寫。

response.set(field, value)

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

response.append(field, value)

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

res.set(fields)

使用對象同時設置 response header 中多個字段的值。

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

res.remove(field)

移除 response header 中字段 filed

res.type

獲取 response Content-Type,不包含像 "charset" 這樣的參數。

response.type=

經過 mime 類型的字符串或者文件擴展名設置 response Content-Type

response.is(types...)

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

app.use(function * minifyHTML(next) {
  yield 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);
});

res.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] 狀態,直接在重定向以前或者以後執行便可。若是要修改 body,須要在重定向以前執行。

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

res.attachment([filename])

設置 "attachment" 的 Content-Disposition,用於給客戶端發送信號來提示下載。filename 爲可選參數,用於指定下載文件名。

res.headerSent

檢查 response header 是否已經發送,用於在發生錯誤時檢查客戶端是否被通知。

res.lastModified

若是存在 Last-Modified,則以 Date 的形式返回。

res.lastModified=

以 UTC 格式設置 Last-Modified。您能夠使用 Date 或 date 字符串來進行設置。

this.response.lastModified = new Date();

res.etag=

設置 包含 "s 的 ETag。注意沒有對應的 res.etag 來獲取其值。

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

res.append(field, val)

在 header 的 field 後面 追加 val

res.vary(field)

至關於執行res.append('Vary', field)。

相關文章
相關標籤/搜索