null=elogin_error code ml058ecode5

Koajs - 下一代 Node.js web 框架简介由 Express 原班人马打造的 koa,致力于成为一个更小、更健壮、更富有表现力的 Web 框架。使用 koa 编写 web 应用,通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套,并极大地提升常用错误处理效率。Koa 不在内核方法中绑定任何中间件,它仅仅提供了一个轻量优雅的函数库,使得编写 Web 应用变得得心应手。
Koa 当前需要 node 0.11.x 并开启 --harmony (或--harmony-generators), 因为它依赖于 ES6 的 generator 特性. 如果你的当前 Node 版本小于 0.11, 可以通过
(node 版本管理工具) 快速安装 0.11.x
$ npm install -g n
$ n 0.11.12
$ node --harmony my-koa-app.js
为了方便,可以将 node 设置为默认启动 harmony 模式的别名:
alias node='node --harmony'
还可以使用
运行程序, 但执行效率会较低.
Application
Koa 应用是一个包含中间件 generator 方法数组的对象。当请求到来时, 这些方法会以 stack-like 的顺序执行, 从这个角度来看,Koa 和其他中间件系统(比如 Ruby Rack 或者 Connect/Express )非常相似. 然而 Koa 的一大设计理念是: 通过其他底层中间件层提供高级「语法糖」,而不是Koa. 这大大提高了框架的互操作性和健壮性, 并让中间件开发变得简单有趣.
比如内容协商(content-negotation)、缓存控制(cache freshness)、反向代理(proxy support)重定向等常见功能都由中间件来实现. 将类似常见任务分离给中间件实现, Koa 实现了异常精简的代码.
一如既往的 Hello world:
var koa = require('koa');
var app = koa();
app.use(function *(){
this.body = 'Hello World';
app.listen(3000);
译者注: 与普通的 function 不同,generator functions 以 function* 声明。以这种关键词声明的函数支持 yield
代码级联(Cascading)
Koa 中间件以一种更加传统的方式级联起来, 跟你在其他系统或工具中碰到的方式非常相似。
然而在以往的 Node 开发中, 级联是通过回调实现的, 想要开发用户友好的代码是非常困难的,
Koa 借助 generators 实现了真正的中间件架构, 与 Connect 实现中间件的方法相对比,Koa 的做法不是简单的将控制权依次移交给一个又一个的方法直到某个结束,Koa 执行代码的方式有点像回形针,用户请求通过中间件,遇到 yield next 关键字时,会被传递到下游中间件(downstream),在 yield next 捕获不到下一个中间件时,逆序返回继续执行代码(upstream)。
下边这个简单返回 Hello World 的例子可以很好说明 Koa 的中间件机制:一开始,请求经过 x-response-time 和 logging 中间件,记录了请求的开始时间,然后将控制权 yield 给 response 中间件. 当一个中间件执行 yield next时,该方法会暂停执行并把控制权传递给下一个中间件,当没有下一个中间件执行 downstream 的时候,代码将会逆序执行所有流过中间件的 upstream 代码。
var koa = require('koa');
var app = koa();
// x-response-time
app.use(function *(next){
var start = new D
var ms = new Date -
this.set('X-Response-Time', ms + 'ms');
app.use(function *(next){
var start = new D
var ms = new Date -
console.log('%s %s - %s', this.method, this.url, ms);
// response
app.use(function *(){
this.body = 'Hello World';
app.listen(3000);
.middleware1 {
// (1) do some stuff
.middleware2 {
// (2) do some other stuff
.middleware3 {
// (3) NO next yield !
// this.body = 'hello world'
// (4) do some other stuff later
// (5) do some stuff lastest and return
上方的伪代码中标注了中间件的执行顺序,看起来是不是有点像 ruby 执行代码块(block)时 yield 的表现了?也许这能帮助你更好的理解 koa 运作的方式。
译者注: 更加形象的图可以参考
配置(Settings)
应用配置是 app 实例的属性, 目前支持以下配置:
app.name 应用名称
app.env 默认是 NODE_ENV 或者 &development&
app.proxy 决定了哪些 proxy header 参数会被加到信任列表中
app.subdomainOffset 被忽略的 .subdomains 列表,详见下方 api
app.listen(...)
一个 Koa 应用跟 HTTP server 不是 1-to-1 关系, 一个或多个 Koa 应用可以被加载到一块
组成一个更大的包含一个 HTTP server 的应用.
该方法创建并返回一个 http server, 并且支持传递固定参数
Server#listen(). 具体参数可查看 . 如下为一个监听 3000 端口的简单应用:
var koa = require('koa');
var app = koa();
app.listen(3000);
方法 app.listen(...) 是一个语法糖, 等价于:
var http = require('http');
var koa = require('koa');
var app = koa();
http.createServer(app.callback()).listen(3000);
这意味着你可以同时支持 HTTP 和 HTTPS, 或在多个地址上使用同一个 app.
var http = require('http');
var koa = require('koa');
var app = koa();
http.createServer(app.callback()).listen(3000);
http.createServer(app.callback()).listen(3001);
app.callback()
返回一个回调方法能用于 http.createServer() 来处理请求,也可以将这个回调函数挂载到 Connect/Express 应用上。
app.use(function)
将给定的 function 当做中间件加载到应用中,详见
设置 Cookie 签名密钥。
这些值会被传递给
如果你想自己生成一个实例,也可以这样:
app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');
注意,签名密钥只在配置项 signed 参数为真是才会生效:
this.cookies.set('name', 'tobi', { signed: true });
错误处理(Error Handling)
除非应用执行环境(NODE_ENV)被配置为 &test&,Koa 都将会将所有错误信息输出到 stderr. 如果想自定义错误处理逻辑, 可以定义一个「错误事件」来监听 Koa app 中发生的错误:
app.on('error', function(err){
log.error('server error', err);
当 req/res 周期中出现任何错误且无法响应客户端时,Koa 会把 Context(上下文) 实例作为第二个参数传递给 error 事件:
app.on('error', function(err, ctx){
log.error('server error', err, ctx);
如果有错误发生, 并且还能响应客户端(即没有数据被写入到 socket), Koa 会返回 500 &Internal Server Error&.
这两种情况都会触发 app-level 的 error 事件, 用于 logging.
Koa 的 Context 把 node 的 request, response 对象封装进一个单独对象, 并提供许多开发 web 应用和 APIs 有用的方法.
那些在 HTTP server 开发中使用非常频繁操作, 直接在 Koa 里实现,
而不是放在更高层次的框架, 这样中间件就不需要重复实现这些通用的功能.
每个 请求会创建自己的 Context 实例, 在中间件中作为 receiver 引用, 或通过 this 标示符引用. 如.
app.use(function *(){
// is the Context
this. // is a koa Request
this. // is a koa Response
Context 的许多访问器和方法直接委托为他们的 ctx.request 或 ctx.response 的
等价方法, 用于访问方便, 是完全相同的. 比如ctx.type 和 ctx.length
委托与 response 对象, ctx.path 和 ctx.method 委托与 request.
Context 详细方法和访问器.
Node 的 request 对象.
Node 的 response 对象.
绕开 Koa 的 response 处理 是 不支持的. 避免使用如下 node 属性:
res.statusCode
res.writeHead()
res.write()
ctx.request
koa Request 对象.
ctx.response
koa Response 对象.
应用实例引用.
ctx.cookies.get(name, [options])
获取名为 name 带有 options 的 cookie:
signed 请求的 cookie 应该是被 signed
模块, options 被直接传递过去.
ctx.cookies.set(name, value, [options])
设置 cookie name 为 value 带有 options:
signed sign cookie 值
expires cookie 过期 Date
path cookie 路径, 默认 /'
domain cookie 域名
secure secure cookie
httpOnly server 才能访问 cookie, 默认 true
模块, options 被直接传递过去.
ctx.throw([msg], [status], [properties])
Helper 方法, 抛出包含 .status 属性的错误, 默认为 500. 该方法让 Koa 能够合适的响应.
并且支持如下组合:
this.throw(403)
this.throw('name required', 400)
this.throw(400, 'name required')
this.throw('something exploded')
例如 this.throw('name required', 400) 等价于:
var err = new Error('name required');
err.status = 400;
注意这些是 user-level 的错误, 被标记为 err.expose, 即这些消息可以用于 client 响应,
而不是 error message 的情况, 因为你不想泄露失败细节.
你可以传递一个 properties 对象, 该对象会被合并到 error 中, 这在修改传递给上游中间件的机器友好错误时非常有用
this.throw(401, 'access_denied', { user: user });
this.throw('access_denied', { user: user });
创建错误对象.
ctx.assert(value, [msg], [status], [properties])
抛出错误的 Helper 方法, 跟 .throw() 相似
当 !value. 跟 node 的
this.assert(this.user, 401, 'User not found. Please login!');
ctx.respond
如不想使用 koa 内置的 response 处理方法, 可以设置 this.respond =. 这时你可以自己设置 res 对象.
注意这样使用是不被 Koa 支持的. 这样有可能会破坏 Koa 的中间件和 Koa 本身内部功能. 这种用法只是作为一种 hack 方式, 给那些想在 Koa 中间件和方法内使用传统的fn(req, res) 一种方式
Request 别名
如下访问器和别名同
ctx.header
ctx.headers
ctx.method
ctx.method=
ctx.originalUrl
ctx.query=
ctx.querystring
ctx.querystring=
ctx.hostname
ctx.socket
ctx.protocol
ctx.secure
ctx.subdomains
ctx.accepts()
ctx.acceptsEncodings()
ctx.acceptsCharsets()
ctx.acceptsLanguages()
Response 别名
如下访问器和别名同
ctx.status
ctx.status=
ctx.length=
ctx.length
ctx.headerSent
ctx.redirect()
ctx.attachment()
ctx.remove()
ctx.lastModified=
Koa Request 对象是 node 普通 request 对象之上的抽象, 提供了日常 HTTP server 中更多有用的功能.
请求头对象.
req.header 的别名
req.method
req.method=
设置请求方法, 实现中间件时非常有用, 例如 methodOverride().
req.length
将请求的 Content-Length 返回为数字, 或 undefined.
获取请求 URL.
设置请求 URL, 在 rewrites 时有用.
req.originalUrl
获取 original URL.
获取请求 pathname.
设置请求 pathname, 如果有 query-string 则保持不变.
req.querystring
获取原始 query string, 不包含 ?.
req.querystring=
设置 query string.
获取原始 query string, 包含 ?.
设置 query string.
获取 host, 不包含端口号. 当 app.proxy 为 true 时支持 X-Forwarded-Host, 否者就使用 Host.
req.hostname
获取 hostname 如果有的话. 当 app.proxy 设为 true 时支持 X-Forwarded-Host, 否则直接使用 Host.
获取请求 Content-Type 字段, 不包含参数, 如 &charset&.
var ct = this.
// =& &image/png&
req.charset
获取请求 charset, 没有返回 undefined
this.request.charset
// =& &utf-8&
获取解析后的 query-string, 如果没有返回空对象. 注意: 该方法不支持嵌套解析.
例如 &color=blue&size=small&:
color: 'blue',
size: 'small'
req.query=
根据给定的对象设置 query-string. 注意: 该方法不支持嵌套对象.
this.query = { next: '/login' };
检查请求缓存是否是 &fresh& 的, 即内容没有发生变化. 该方法用于在If-None-Match / ETag, If-Modified-Since, Last-Modified 之间进行缓存 negotiation. 这个应该在设置过这些响应 hearder 后会用到.
this.set('ETag', '123');
// cache is ok
if (this.fresh) {
this.status = 304;
// cache is stale
// fetch new data
this.body = yield db.find('something');
相反与 req.fresh.
req.protocol
返回请求协议, &https& 或 &http&. 当 app.proxy 为 true 时支持 X-Forwarded-Proto.
req.secure
简化版 this.protocol == &https& 用于检查请求是否通过 TLS 发送.
请求 IP 地址. 当 app.proxy 为 true 时支持 X-Forwarded-Proto.
当 X-Forwarded-For 存在并且 app.proxy 开启会返回一个有序(upstream -& downstream)的 ip 数组.
否则返回空数组.
req.subdomains
以数组形式返回子域名.
子域名是 host 逗号分隔主域名前面的部分. 默认主域名是 host 的最后两部分. 可以通过设置 app.subdomainOffset 调整.
例如, 架设域名是 &tobi.&:
如果 app.subdomainOffset 没有设置, this.subdomains 为 [&ferrets&, &tobi&].
如果 app.subdomainOffset 设为 3, this.subdomains 为 [&tobi&].
req.is(type)
检查请求是否包含 &Content-Type& 字段, 并且包含当前已知的 mime 'type'.
如果没有请求 body, 返回 undefined.
如果没有字段, 或不包含, 返回 false.
否则返回包含的 content-type.
// With Content-Type: text/ charset=utf-8
this.is('html'); // =& 'html'
this.is('text/html'); // =& 'text/html'
this.is('text/*', 'text/html'); // =& 'text/html'
// When Content-Type is application/json
this.is('json', 'urlencoded'); // =& 'json'
this.is('application/json'); // =& 'application/json'
this.is('html', 'application/*'); // =& 'application/json'
this.is('html'); // =& false
例如, 如果你想确保指定的路由只返回图片.
if (this.is('image/*')) {
// process
this.throw(415, 'images only!');
Content Negotiation
Koa 的 请求 对象包含有用的内容 negotiation 方法, 这些方法由 和
提供, 主要包括:
req.accepts(types)
req.acceptsEncodings(types)
req.acceptsCharsets(charsets)
req.acceptsLanguages(langs)
如果没有提供 types, 将会返回所有支持的 type
如果提供多个 type, 将会返回最符合的那个, 如果没有符合的类型, 将会返回 false, 这时你应该响应 406 &Not Acceptable& 给客户端
如果没有 accept headers, 即被认为可以接受任何 type, 会返回第一个 type, 这时提供的 type 顺序会非常重要
req.accepts(types)
检查给定的 type(s) 是否 acceptable, 如果是, 则返回最佳的匹配, 否则 false,
这时应该响应 406 &Not Acceptable&.
type 值应该是一个或多个 mime 字符串, 例如 &application/json&, 扩展名如 &json&, 或数组 [&json&, &html&, &text/plain&].
如果给定一个 list 或 array, 会返回最佳(best)匹配项.
如果请求 client 没有发送 Accept header, 会返回第一个 type.
// Accept: text/html
this.accepts('html');
// =& &html&
// Accept: text/*, application/json
this.accepts('html');
// =& &html&
this.accepts('text/html');
// =& &text/html&
this.accepts('json', 'text');
// =& &json&
this.accepts('application/json');
// =& &application/json&
// Accept: text/*, application/json
this.accepts('image/png');
this.accepts('png');
// =& false
// Accept: text/*;q=.5, application/json
this.accepts(['html', 'json']);
this.accepts('html', 'json');
// =& &json&
// No Accept header
this.accepts('html', 'json');
// =& &html&
this.accepts('json', 'html');
// =& &json&
this.accepts() 可以被多次调用, 或使用在 switch.
switch (this.accepts('json', 'html', 'text')) {
case 'json':
case 'html':
case 'text':
default: this.throw(406, 'json, html, or text only');
req.acceptsEncodings(encodings)
检查 encodings 是否被接受, 如果是返回最佳匹配, 否则返回 identity.
// Accept-Encoding: gzip
this.acceptsEncodings('gzip', 'deflate', 'identity');
// =& &gzip&
this.acceptsEncodings(['gzip', 'deflate', 'identity']);
// =& &gzip&
如果没有传递参数, 会返回所有可接受的 encodings 数组.
// Accept-Encoding: gzip, deflate
this.acceptsEncodings();
// =& [&gzip&, &deflate&, &identity&]
注意 identity 编码 (等同于没有编码) 不会被接受, 如果客户端明确的发送了 q=0. 虽然这种情况很少发生, 但你需要手动处理该方法返回
false 情况.
req.acceptsCharsets(charsets)
检查 charsets 是否被接受, 如果是返回最佳匹配, 否则 undefined.
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets('utf-8', 'utf-7');
// =& &utf-8&
this.acceptsCharsets(['utf-7', 'utf-8']);
// =& &utf-8&
如果没有传递参数, 会返回所有可接受 charsets 数组.
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets();
// =& [&utf-8&, &utf-7&, &iso-8859-1&]
req.acceptsLanguages(langs)
检查 langs 是否被接受, 如果是返回最佳匹配, 否则返回 undefined.
// Accept-Language:q=0.8, es, pt
this.acceptsLanguages('es', 'en');
// =& &es&
this.acceptsLanguages(['en', 'es']);
// =& &es&
如果没有传递参数, 会返回所有可接受的 lang 数组.
// Accept-Language:q=0.8, es, pt
this.acceptsLanguages();
// =& [&es&, &pt&, &en&]
req.idempotent
判断请求是否是 idempotent.
req.socket
返回请求 socket.
req.get(field)
返回请求 header.
Koa Request 对象是 node 普通 request 对象之上的抽象, 提供了日常 HTTP server 中有用的功能.
请求头对象.
req.method
req.method=
设置请求方法, 实现中间件时非常有用, 例如 methodOverride().
req.length
将请求的 Content-Length 返回为数字, 或 undefined.
获取请求 URL.
设置请求 URL, 在 rewrites 时有用.
获取请求 pathname.
设置请求 pathname, 如果有 query-string 则保持不变.
req.querystring
获取原始 query string, 不包含 ?.
req.querystring=
设置 query string.
获取原始 query string, 包含 ?.
设置 query string.
获取 host, 不包含端口号. 当 app.proxy 为 true 时支持 X-Forwarded-Host, 否者就使用 Host.
设置 Host 头字段.
获取请求 Content-Type 字段, 不包含参数, 如 &charset&.
var ct = this.
// =& &image/png&
req.charset
获取请求 charset, 没有返回 undefined
获取解析后的 query-string, 如果没有返回空对象. 注意: 该方法不支持嵌套解析.
例如 &color=blue&size=small&:
color: 'blue',
size: 'small'
req.query=
根据给定的对象设置 query-string. 注意: 该方法不支持嵌套对象.
this.query = { next: '/login' };
检查请求缓存是否是 &fresh& 的, 即内容没有发生变化. 该方法用于在If-None-Match / ETag, If-Modified-Since, Last-Modified 之间进行缓存 negotiation. 这个应该在设置过这些响应 hearder 后会用到.
this.set('ETag', '123');
// cache is ok
if (this.fresh) {
this.status = 304;
// cache is stale
// fetch new data
this.body = yield db.find('something');
相反与 req.fresh.
req.protocol
返回请求协议, &https& 或 &http&. 当 app.proxy 为 true 时支持 X-Forwarded-Proto.
req.secure
简化版 this.protocol == &https& 用于检查请求是否通过 TLS 发送.
请求 IP 地址. 当 app.proxy 为 true 时支持 X-Forwarded-Proto.
当 X-Forwarded-For 存在并且 app.proxy 开启会返回一个有序(upstream -& downstream)的 ip 数组.
否则返回空数组.
req.subdomains
以数组形式返回子域名.
子域名是 host 逗号分隔主域名前面的部分. 默认主域名是 host 的最后两部分. 可以通过设置 app.subdomainOffset 调整.
例如, 架设域名是 &tobi.&:
如果 app.subdomainOffset 没有设置, this.subdomains 为 [&ferrets&, &tobi&].
如果 app.subdomainOffset 设为 3, this.subdomains 为 [&tobi&].
req.is(type)
检查请求是否包含 &Content-Type& 字段, 并且包含当前已知的 mime 'type'.
如果没有请求 body, 返回 undefined.
如果没有字段, 或不包含, 返回 false.
否则返回包含的 content-type.
// With Content-Type: text/ charset=utf-8
this.is('html'); // =& 'html'
this.is('text/html'); // =& 'text/html'
this.is('text/*', 'text/html'); // =& 'text/html'
// When Content-Type is application/json
this.is('json', 'urlencoded'); // =& 'json'
this.is('application/json'); // =& 'application/json'
this.is('html', 'application/*'); // =& 'application/json'
this.is('html'); // =& false
例如, 如果你想确保指定的路由只返回图片.
if (this.is('image/*')) {
// process
this.throw(415, 'images only!');
req.accepts(types)
检查给定的 type(s) 是否 acceptable, 如果是, 则返回最佳的匹配, 否则 false,
这时应该响应 406 &Not Acceptable&.
type 值应该是一个或多个 mime 字符串, 例如 &application/json&, 扩展名如 &json&, 或数组 [&json&, &html&, &text/plain&].
如果给定一个 list 或 array, 会返回最佳(best)匹配项.
如果请求 client 没有发送 Accept header, 会返回第一个 type.
// Accept: text/html
this.accepts('html');
// =& &html&
// Accept: text/*, application/json
this.accepts('html');
// =& &html&
this.accepts('text/html');
// =& &text/html&
this.accepts('json', 'text');
// =& &json&
this.accepts('application/json');
// =& &application/json&
// Accept: text/*, application/json
this.accepts('image/png');
this.accepts('png');
// =& undefined
// Accept: text/*;q=.5, application/json
this.accepts(['html', 'json']);
this.accepts('html', 'json');
// =& &json&
this.accepts() 可以被多次调用, 或使用在 switch.
switch (this.accepts('json', 'html', 'text')) {
case 'json':
case 'html':
case 'text':
default: this.throw(406);
req.acceptsEncodings(encodings)
检查 encodings 是否被接受, 如果是返回最佳匹配, 否则返回 identity.
// Accept-Encoding: gzip
this.acceptsEncodings('gzip', 'deflate');
// =& &gzip&
this.acceptsEncodings(['gzip', 'deflate']);
// =& &gzip&
如果没有传递参数, 会返回所有可接受的 encodings 数组.
// Accept-Encoding: gzip, deflate
this.acceptsEncodings();
// =& [&gzip&, &deflate&]
req.acceptsCharsets(charsets)
检查 charsets 是否被接受, 如果是返回最佳匹配, 否则 undefined.
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets('utf-8', 'utf-7');
// =& &utf-8&
this.acceptsCharsets(['utf-7', 'utf-8']);
// =& &utf-8&
如果没有传递参数, 会返回所有可接受 charsets 数组.
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets();
// =& [&utf-8&, &utf-7&, &iso-8859-1&]
req.acceptsLanguages(langs)
检查 langs 是否被接受, 如果是返回最佳匹配, 否则返回 undefined.
// Accept-Language:q=0.8, es, pt
this.acceptsLanguages('es', 'en');
// =& &es&
this.acceptsLanguages(['en', 'es']);
// =& &es&
如果没有传递参数, 会返回所有可接受的 lang 数组.
// Accept-Language:q=0.8, es, pt
this.acceptsLanguages();
// =& [&es&, &pt&, &en&]
req.idempotent
判断请求是否是 idempotent.
req.socket
返回请求 socket.
req.get(field)
返回请求 header.
Koa Response 对象是 node 普通 request 对象之上的抽象, 提供了日常 HTTP server 中有用的功能.
响应 header 对象.
res.socket
请求socket
res.status
返回响应状态. 默认 res.status 没有值, 而不是像 node 的 res.statusCode 默认为 200.
res.status=
使用状态码或不区分大小写的字符串设置响应状态:
100 &continue&
101 &switching protocols&
102 &processing&
201 &created&
202 &accepted&
203 &non-authoritative information&
204 &no content&
205 &reset content&
206 &partial content&
207 &multi-status&
300 &multiple choices&
301 &moved permanently&
302 &moved temporarily&
303 &see other&
304 &not modified&
305 &use proxy&
307 &temporary 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 time-out&
409 &conflict&
410 &gone&
411 &length required&
412 &precondition failed&
413 &request entity too large&
414 &request-uri too large&
415 &unsupported media type&
416 &requested range not satisfiable&
417 &expectation failed&
418 &i'm a teapot&
422 &unprocessable entity&
423 &locked&
424 &failed dependency&
425 &unordered collection&
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 time-out&
505 &http version not supported&
506 &variant also negotiates&
507 &insufficient storage&
509 &bandwidth limit exceeded&
510 &not extended&
511 &network authentication required&
注意: 不用担心没法记住这些状态码, 如果设置错误, 会有异常抛出, 并列出该状态码表,
从而帮助修改.
res.length=
设置响应 Content-Length.
res.length
如果 Content-Length 存在返回相应数值, 或通过 res.body 计算得出, 否则返回 undefined.
返回响应内容.
设置响应内容为如下值:
string written
Buffer written
Stream piped
Object json-stringified
null no content response
如果 res.status 没有设置, Koa 会自动设定 status 为 200 或 204.
Content-Type 默认设置为 text/html 或 text/plain, 两个的编码都是 utf-8. Content-Length 同样会被设置.
Content-Type 默认设置为 application/octet-stream, 并设置 Content-Length.
Content-Type 默认设置为 application/octet-stream.
Content-Type 默认设置为 to application/json.
res.get(field)
获取响应头部字段值, field 区分大小写.
var etag = this.get('ETag');
res.set(field, value)
设置响应头部字段 field 为 value:
this.set('Cache-Control', 'no-cache');
res.set(fields)
使用对象同时设置多个响应头 fields
this.set({
'Etag': '1234',
'Last-Modified': date
res.remove(field)
删除头部 field 字段.
获取响应 Content-Type 字段, 不包含参数如 &charset&.
var ct = this.
// =& &image/png&
通过 mime 字符串或文件扩展名设置响应 Content-Type.
this.type = 'text/ charset=utf-8';
this.type = 'image/png';
this.type = '.png';
this.type = 'png';
注意: 当合适的 charset 可以确定, 会自动设置, 例如 res.type = 'html'
会自动设置为 &utf-8&, 但是如果设置完整时, charset 不会自动设定,
如 res.type = 'text/html'.
res.is(types...)
跟 this.request.is() 非常相似.
检查响应 type 是否是提供的 types 之一.
该方法在开发修改响应内容的中间件时非常有用
例如这是一个压缩 html 响应的中间件, 他不会处理 streams 类型.
var minify = require('html-minifier');
app.use(function *minifyHTML(next){
if (!this.response.is('html'))
var body = this.
if (!body || body.pipe)
if (Buffer.isBuffer(body)) body = body.toString();
this.body = minify(body);
res.redirect(url, [alt])
执行 [302] 重定向到 url.
字符 &back& 是一种特殊用法, 能提供 Referrer支持, 当没有 Referrer时 使用alt 或 &/&
this.redirect('back');
this.redirect('back', '/index.html');
this.redirect('/login');
this.redirect('');
如果想要修改默认状态 302, 直接在重定向之前或之后设定 status, 如果想修改 body , 需要
在重定向之后执行.
this.status = 301;
this.redirect('/cart');
this.body = 'Redirecting to shopping cart';
res.attachment([filename])
设置 &attachment&
的 Content-Disposition 用于给客户端发送信号, 提示下载.
下载文件的名字可以通过参数设置.
检查响应头是否已经发送. 在有错误时检查 client 是否被通知时有用.
res.lastModified
如果响应头部包含 Last-Modified, 返回 Date.
res.lastModified=
将 Last-Modified 头部设置为正确的 UTC string. 可以使用 Date 或 date 字符串设置.
this.response.lastModified = new Date();
设置响应的 ETag (包括 wrapped &). 注意没有对应的 res.etag 获取器.
this.response.etag = crypto.createHash('md5').update(this.body).digest('hex');
res.vary(field)
Vary on field.
这节内容跟 API 无关, 而是中间件开发最佳实践, 应用架构建议等.
开发中间件
Koa 中间件是返回 GeneratorFunction 的方法, 并接受其他的中间件. 当某个中间件被 &upstream& 中间件执行时, 它必须手动 yield
&downstream& 中间件
例如你想记录 request 传递经过 Koa 的时间, 可以开发一个添加 X-Response-Time 头字段的中间件.
function *responseTime(next){
var start = new D
var ms = new Date -
this.set('X-Response-Time', ms + 'ms');
app.use(responseTime);
如下是一个等价的 inline 中间件:
app.use(function *(next){
var start = new D
var ms = new Date -
this.set('X-Response-Time', ms + 'ms');
如果你是一个前端工程师, 可以把所有
之前的代码看做 &capture& 阶段, 把之后的代码看做 &bubble& 阶段.
如下 gif 展示了 ES6 generators 如何让我们合理的使用 stack flow 实现 request and response flows:
创建 date 记录花费时间
将控制 Yield 到下一个 middleware
创建另外 date 记录响应时间
将控制 Yield 到下一个 middleware
立刻 Yield 控制, 因为 contentLength 只对 response 起作用
将 upstream Yield 到 Koa 的 空middleware.
如果请求路径不是 &/&, 则跳过设置 body.
设置响应为 &Hello World&
如果有 body 则设置 Content-Length
设置头部字段
发送响应前设置 X-Response-Time 头字段
转会 Koa, Koa负责发送 response
注意最后的中间件 (step 6) yields, 看起来没有转给任何东西, 但实际上他转给了 Koa 的空 generator. 这是为了保证所有
的中间件遵循相同的 API, 可以在其他中间件前边或后边使用. 如果你删掉最深 &downstream& 中间件的
所有的功能
都还 OK, 但是不在遵循这个行为.
例如如下代码也不会出错:
app.use(function *response(){
if ('/' != this.url)
this.body = 'Hello World';
接下来是中间件开发最佳实践
中间件最佳实践
这个环节介绍了中间件开发最佳实践相关内容: 可接受的选项, 给中间件命名有利于调试, 及其他.
中间件选项
在开发中间件时遵循惯例是非常重要的: 使用接受参数的方法 wrapping 中间件, 这样用户可以扩展功能.
即使你的中间件不接受选项, 保持所有事情一致也是最好的选择.
如下是一个 logger 中间件, 接受 format 字符串, 用于自定义格式, 最后返回中间件.
function logger(format){
format = format || ':method &:url&';
return function *(next){
var str = format
.replace(':method', this.method)
.replace(':url', this.url);
console.log(str);
app.use(logger());
app.use(logger(':method :url'));
给中间件命名
中间件命名不是强制的, 但如果中间件有名字, 在调试时会非常有帮助.
function logger(format){
return function *logger(next){
将多个中间件组合为一个
有时候你需要将多个中间件组合成一个, 从而方便重用或 exporting. 这时你可以用 .call(this, next) 将他们连起来, 然后将 yield 这个 chain 的方法返回.
function *random(next){
if ('/random' == this.path) {
this.body = Math.floor(Math.random()*10);
function *backwords(next) {
if ('/backwords' == this.path) {
this.body = 'sdrowkcab';
function *pi(next){
if ('/pi' == this.path) {
this.body = String(Math.PI);
function *all(next) {
yield random.call(this, backwords.call(this, pi.call(this, next)));
app.use(all);
Koa 内部 使用 koa-compose 创建和调度中间件栈.
内部就是这样实现的.
响应中间件
如果中间件用于响应请求, 需要跳过 downstream 的中间件可以直接省略 yield next. 通常路由中间件就是这样的, 而且在所有中间件里都可以省略.
例如下面的例子会响应 &two&, 但是三个都被执行了, 所以在 downstream &three& 中间件里就有可能修改响应结果.
app.use(function *(next){
console.log('&& one');
console.log('&& one');
app.use(function *(next){
console.log('&& two');
this.body = 'two';
console.log('&& two');
app.use(function *(next){
console.log('&& three');
console.log('&& three');
The following configuration omits yield next in the second middleware, and will still respond
with &two&, however the third (and any other downstream middleware) will be ignored:
在下面的例子中第二个中间件省略了 yield next, 最终响应结果还是 &two&, 但是第三个(以后后面所有的 downstream 中间件)中间件被忽略了.
app.use(function *(next){
console.log('&& one');
console.log('&& one');
app.use(function *(next){
console.log('&& two');
this.body = 'two';
console.log('&& two');
app.use(function *(next){
console.log('&& three');
console.log('&& three');
当最深的中间件执行 , 它实际上是 yield 的空方法, 这样可以保证 stack 中所有地方的中间件可以正常 compose.
构成了 Koa generator 委托的基石. 让我们可以写非阻塞的顺序代码.
例如如下代码. 读取 ./docs 中的所有文件名, 并读取所有 markdown 的内容, 连接后赋给 body, 这所有的异步操作都是使用
顺序代码实现的.
var fs = require('co-fs');
app.use(function *(){
var paths = yield fs.readdir('docs');
var files = yield paths.map(function(path){
return fs.readFile('docs/' + path, 'utf8');
this.type = 'markdown';
this.body = files.join('');
Koa 和许多相关的库都支持 DEBUG 环境变量. 这是通过
实现的, debug 提供简单的条件 logging.
例如, 如果想查看所有 koa 调试信息, 设置环境变量为 DEBUG=koa*, 这样在程序启动的时候, 可以看到所有使用的中间件列表.
$ DEBUG=koa* node --harmony examples/simple
koa:application use responseTime +0ms
koa:application use logger +4ms
koa:application use contentLength +0ms
koa:application use notfound +0ms
koa:application use response +0ms
koa:application listen +0ms
虽然 JavaScript 不允许动态定义方法名, 但是你可以将中间件的名字设置为 ._name.
这在你无法修改中间件名字时非常有用如:
var path = require('path');
var static = require('koa-static');
var publicFiles = static(path.join(__dirname, 'public'));
publicFiles._name = 'static /public';
app.use(publicFiles);
现在, 在调试模式你不仅可以看到 &static&, 还能:
koa:application use static /public +0ms
相关链接相关社区, 可以发现Koa第三方中间件, 完整可运行例子, 简明的指导,以及更多.
如果发现问题可以在IRC上提出讨论.
#koajs on freenode}

我要回帖

更多关于 300英雄null elogin4 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信