国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片

Koajs 備忘清單

NPM version Downloads Repo Dependents Github repo

基于 Node.js 平臺(tái)的下一代 web 開(kāi)發(fā)框架,包含 Koa 的 API 參考列表和一些示例

入門(mén)

Hello World

Koa 需要 node v7.6.0 或更高版本來(lái)支持ES2015、異步方法,你可以安裝自己支持的 node 版本

  • 安裝依賴(lài)

    $ mkdir myapp # 創(chuàng)建目錄
    $ cd myapp    # 進(jìn)入目錄
    $ nvm install 7
    $ npm init -y # 初始化一個(gè)配置
    $ npm install koa # 安裝依賴(lài)
    
  • 入口文件 index.js 添加代碼:

    const Koa = require('koa');
    const app = new Koa();
    
    app.use(async ctx => {
      ctx.body = 'Hello World';
    });
    
    app.listen(3000);
    
  • 使用以下命令運(yùn)行應(yīng)用程序

    $ node index.js
    

級(jí)聯(lián)

const Koa = require('koa');
const app = new Koa();
// X-Response-Time x 響應(yīng)時(shí)間
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});
// 記錄器 logger
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(
    `${ctx.method} ${ctx.url} - ${ms}`
  );
});
// 響應(yīng) response
app.use(async ctx => {
  ctx.body = 'Hello World';
});
app.listen(3000);

配置

:-:-
app.env默認(rèn)為 NODE_ENVdevelopment
app.keys簽名 cookie 密鑰數(shù)組
app.proxy何時(shí)信任真正的代理頭字段
app.subdomainOffset要忽略的 .subdomains 的偏移量,默認(rèn)為 2
app.proxyIpHeader代理 ip 頭,默認(rèn)為 X-Forwarded-For
app.maxIpsCount從代理 ip 頭讀取的最大 ips 數(shù),默認(rèn)為 0(表示無(wú)窮大)

app.callback()

:-:-
app.listen(...) #為一個(gè)綁定 3000 端口的簡(jiǎn)單 Koa 應(yīng)用
app.callback() #返回一個(gè)適合 http.createServer() 方法的回調(diào)函數(shù)用來(lái)處理請(qǐng)求
app.use(function) #添加指定的中間件,詳情請(qǐng)看 Middleware
app.keys #設(shè)置簽名 cookie 密鑰
app.context #從中創(chuàng)建 ctx 的原型

錯(cuò)誤處理

app.on('error', (err, ctx) => {
  log.error('server error', err, ctx)
});

默認(rèn)情況下 Koa 會(huì)將所有錯(cuò)誤信息輸出到 stderr, 除非 app.silenttrue。當(dāng) err.status404 或者 err.expose 時(shí),默認(rèn)錯(cuò)誤處理程序也不會(huì)輸出錯(cuò)誤

Context 示例

app.use(async ctx => {
  ctx; // 這是上下文 Context
  ctx.request;  // 這是 koa Request
  ctx.response; // 這是 koa Response
});

app.listen(...)

const Koa = require('koa');
const app = new Koa();
app.listen(3000);

app.listen(...) 實(shí)際上是以下代碼的語(yǔ)法糖:

const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);

這意味著您可以同時(shí)支持 HTTPSHTTPS,或者在 多個(gè)端口 監(jiān)聽(tīng)同一個(gè)應(yīng)用

const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);

ctx.throw 示例

ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });

this.throw('name required', 400) 等價(jià)于

const err = new Error('name required');
err.status = 400;
err.expose = true;
throw err;

ctx.assert 示例

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

Context(上下文) API

:-:-
ctx.reqNode 的 request 對(duì)象
ctx.resNode 的 response 對(duì)象
ctx.requestKoa 的 Request 對(duì)象
ctx.responseKoa 的 Response 對(duì)象
ctx.state推薦的命名空間,用于通過(guò)中間件傳遞信息到前端視圖
ctx.app應(yīng)用實(shí)例引用
ctx.app.emit發(fā)出由第一個(gè)參數(shù)定義的類(lèi)型的事件
ctx.cookies.get(name, [options])獲得 cookie 中名為 name 的值
ctx.cookies.set(name, value, [options])設(shè)置 cookie 中名為 name 的值
ctx.throw([status], [msg], [properties])拋出包含 .status 屬性的錯(cuò)誤,默認(rèn)為 500
ctx.assert(value, [status], [msg], [properties])當(dāng) !value 時(shí), Helper 方法拋出一個(gè)類(lèi)似 .throw() 的錯(cuò)誤
ctx.respond避免使用 Koa 的內(nèi)置響應(yīng)處理功能,您可以直接賦值 this.repond = false

ctx.cookies.set 參數(shù)

:-:-
maxAge表示從Date開(kāi)始的毫秒數(shù) now() 到期。
expires一個(gè) Date 對(duì)象,指示 cookie 的到期日期(默認(rèn)情況下在會(huì)話(huà)結(jié)束時(shí)到期)
path表示 cookie 路徑的字符串(默認(rèn)為/
domain表示 cookie 的域的字符串(無(wú)默認(rèn)值)
secure一個(gè)布爾值,指示 cookie 是否只通過(guò)HTTPS發(fā)送(HTTP默認(rèn)為false,HTTPS默認(rèn)為true)。閱讀有關(guān)此選項(xiàng)的更多信息
httpOnly一個(gè)布爾值,指示cookie是否只通過(guò)HTTP(S)發(fā)送,而不可用于客戶(hù)端 JavaScript(默認(rèn)為true)
sameSite一個(gè)布爾值或字符串,指示cookie是否為“同一站點(diǎn)”cookie(默認(rèn)為false)。這可以設(shè)置為“strict”、“l(fā)ax”、“none”或true(映射為“strect”)
signed一個(gè)布爾值,指示是否對(duì)cookie進(jìn)行簽名(默認(rèn)為false)。如果這是真的,還將發(fā)送另一個(gè)附加了.sig后綴的同名cookie,其中一個(gè)27字節(jié)的url安全base64 SHA1值表示cookie name=cookie值相對(duì)于第一個(gè)Keygrip鍵的哈希值。此簽名密鑰用于在下次收到cookie時(shí)檢測(cè)篡改
overwrite一個(gè)布爾值,指示是否覆蓋以前設(shè)置的同名 cookie(默認(rèn)為false)。如果為true,則在設(shè)置此Cookie時(shí),將從set-Cookie標(biāo)頭中篩選出在同一請(qǐng)求期間設(shè)置的具有相同名稱(chēng)的所有Cookie(無(wú)論路徑或域如何)

請(qǐng)求(Request)

:-:-
request.header請(qǐng)求頭對(duì)象
request.header=設(shè)置請(qǐng)求頭對(duì)象
request.headers請(qǐng)求頭對(duì)象。等價(jià)于 request.header.
request.headers=設(shè)置請(qǐng)求頭對(duì)象。 等價(jià)于request.header=.
request.method請(qǐng)求方法
request.method=設(shè)置請(qǐng)求方法, 在實(shí)現(xiàn)中間件時(shí)非常有用,比如 methodOverride()
request.length以數(shù)字的形式返回 request 的內(nèi)容長(zhǎng)度(Content-Length),或者返回 undefined。
request.url獲得請(qǐng)求url地址.
request.url=設(shè)置請(qǐng)求地址,用于重寫(xiě)url地址時(shí)
request.originalUrl獲取請(qǐng)求原始地址
request.origin獲取URL原始地址, 包含 protocol 和 host
request.href獲取完整的請(qǐng)求URL, 包含 protocol, host 和 url
request.path獲取請(qǐng)求路徑名
request.path=設(shè)置請(qǐng)求路徑名并保留當(dāng)前查詢(xún)字符串
request.querystring獲取查詢(xún)參數(shù)字符串(url中?后面的部分),不包含?
request.querystring=設(shè)置原始查詢(xún)字符串
request.search獲取查詢(xún)參數(shù)字符串,包含?
request.search=設(shè)置原始查詢(xún)字符串
request.host獲取 host (hostname:port)。 當(dāng) app.proxy 設(shè)置為 true 時(shí),支持 X-Forwarded-Host
request.hostname獲取 hostname。當(dāng) app.proxy 設(shè)置為 true 時(shí),支持 X-Forwarded-Host。
request.URL獲取 WHATWG 解析的對(duì)象.
request.type獲取請(qǐng)求 Content-Type,不包含像 "charset" 這樣的參數(shù)。
request.charset獲取請(qǐng)求 charset,沒(méi)有則返回 undefined
request.query將查詢(xún)參數(shù)字符串進(jìn)行解析并以對(duì)象的形式返回,如果沒(méi)有查詢(xún)參數(shù)字字符串則返回一個(gè)空對(duì)象
request.query=根據(jù)給定的對(duì)象設(shè)置查詢(xún)參數(shù)字符串
request.fresh檢查請(qǐng)求緩存是否 "fresh"(內(nèi)容沒(méi)有發(fā)生變化)
request.stale與 req.fresh 相反
request.protocol返回請(qǐng)求協(xié)議,"https" 或者 "http"
request.secure簡(jiǎn)化版 this.protocol == "https",用來(lái)檢查請(qǐng)求是否通過(guò) TLS 發(fā)送
request.ip請(qǐng)求遠(yuǎn)程地址,當(dāng) app.proxy 設(shè)置為 true 時(shí),支持 X-Forwarded-Host
request.ips當(dāng) X-Forwarded-For 存在并且 app.proxy 有效,將會(huì)返回一個(gè)有序(從 upstream 到 downstream)ip 數(shù)組
request.subdomains以數(shù)組形式返回子域名
request.is(types...)檢查請(qǐng)求所包含的 "Content-Type" 是否為給定的 type 值
request.accepts(types)檢查給定的類(lèi)型 types(s) 是否可被接受,當(dāng)為 true 時(shí)返回最佳匹配,否則返回 false
request.acceptsEncodings(encodings)檢查 encodings 是否可以被接受,當(dāng)為 true 時(shí)返回最佳匹配,否則返回 false
request.acceptsCharsets(charsets)檢查 charsets 是否可以被接受,如果為 true 則返回最佳匹配,否則返回 false
request.acceptsLanguages(langs)檢查 langs 是否可以被接受,如果為 true 則返回最佳匹配,否則返回 false
request.idempotent檢查請(qǐng)求是否為冪等(idempotent)
request.socket返回請(qǐng)求的socket
request.get(field)返回請(qǐng)求頭

響應(yīng)(Response)

:-:-
response.headerResponse header 對(duì)象
response.headersResponse header 對(duì)象。等價(jià)于 response.header.
response.socketRequest socket.
response.status獲取響應(yīng)狀態(tài)。 默認(rèn)情況下,response.status設(shè)置為404,而不像node's res.statusCode默認(rèn)為200。
response.status=通過(guò)數(shù)字設(shè)置響應(yīng)狀態(tài)
response.message獲取響應(yīng)狀態(tài)消息。默認(rèn)情況下, response.message關(guān)聯(lián)response.status。
response.message=將響應(yīng)狀態(tài)消息設(shè)置為給定值。
response.length=將響應(yīng)Content-Length設(shè)置為給定值。
response.length如果 Content-Length 作為數(shù)值存在,或者可以通過(guò) ctx.body 來(lái)進(jìn)行計(jì)算,則返回相應(yīng)數(shù)值,否則返回 undefined。
response.body獲取響應(yīng)體。
response.body=設(shè)置響應(yīng)體為如 string,Buffer,Stream,Object|Array,null
response.get(field)獲取 response header 中字段值,field 不區(qū)分大小寫(xiě)
response.set(field, value)設(shè)置 response header 字段 field 的值為 value
response.append(field, value)添加額外的字段field 的值為 val
response.set(fields)使用對(duì)象同時(shí)設(shè)置 response header 中多個(gè)字段的值
response.remove(field)移除 response header 中字段 filed
response.type獲取 response Content-Type,不包含像"charset"這樣的參數(shù)
response.type=通過(guò) mime 類(lèi)型的字符串或者文件擴(kuò)展名設(shè)置 response Content-Type
response.is(types...)ctx.request.is() 非常類(lèi)似。用來(lái)檢查響應(yīng)類(lèi)型是否是所提供的類(lèi)型之一
response.redirect(url, [alt])執(zhí)行 [302] 重定向到對(duì)應(yīng) url
response.attachment([filename])設(shè)置 "attachment" 的 Content-Disposition,用于給客戶(hù)端發(fā)送信號(hào)來(lái)提示下載
response.headerSent檢查 response header 是否已經(jīng)發(fā)送,用于在發(fā)生錯(cuò)誤時(shí)檢查客戶(hù)端是否被通知。
response.lastModified如果存在 Last-Modified,則以 Date 的形式返回。
response.lastModified=以 UTC 格式設(shè)置 Last-Modified。您可以使用 Date 或 date 字符串來(lái)進(jìn)行設(shè)置。
response.etag=設(shè)置 包含 "s 的 ETag
response.vary(field)不同于field.
response.flushHeaders()刷新任何設(shè)置的響應(yīng)頭,并開(kāi)始響應(yīng)體

請(qǐng)求(Request)別名

以下訪問(wèn)器和別名與 Request 等價(jià):

  • 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()

響應(yīng)(Response)別名

以下訪問(wèn)器和別名與 Response 等價(jià):

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

request.fresh 示例

// freshness 檢查需要狀態(tài) 20x 或 304
ctx.status = 200;
ctx.set('ETag', '123');

// 緩存正常
if (ctx.fresh) {
  ctx.status = 304;
  return;
}

// 緩存已過(guò)時(shí)
// 獲取新數(shù)據(jù)
ctx.body = await db.find('something');

ctx.is 示例

// Content-Type: text/html; charset=utf-8
ctx.is('html'); // => 'html'
ctx.is('text/html'); // => 'text/html'
ctx.is('text/*', 'text/html');
// => 'text/html'
// 當(dāng) Content-Type 為 application/json 時(shí)
ctx.is('json', 'urlencoded'); // => 'json'
ctx.is('application/json');
// => 'application/json'
ctx.is('html', 'application/*');
// => 'application/json'

ctx.is('html'); // => false

ctx.accepts 示例

// 接受: text/*, application/json
ctx.accepts('html');
// => "html"
ctx.accepts('text/html');
// => "text/html"
ctx.accepts('json', 'text');
// => "json"
ctx.accepts('application/json');
// => "application/json"

request.acceptsCharsets 示例

// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"

ctx.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"

檢查 charsets 是否可以被接受,如果為 true 則返回最佳匹配, 否則返回 false

response.set 示例

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

使用對(duì)象同時(shí)設(shè)置 response header 中多個(gè)字段的值

response.type 示例

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

獲取 response Content-Type,不包含像"charset"這樣的參數(shù)