Koa 需要 Node v12 或更高版本才能支持 ES2015 和异步函数。
¥Koa requires
node v12
or higher for ES2015 and async function support.
你可以使用你最喜欢的版本管理器快速安装受支持的 Node 版本:
¥You can quickly install a supported version of Node with your favorite version manager:
$ nvm install 12
$ npm i koa
$ node my-koa-app.js
¥Application
Koa 应用是一个包含中间件函数数组的对象,这些中间件函数根据请求以类似堆栈的方式组合和执行。Koa 与你可能遇到的许多其他中间件系统类似,例如 Ruby 的 Rack、Connect 等 - 然而,我们做出了一个关键的设计决策,即在底层中间件层提供高级别 "糖"。这提高了互操作性、健壮性,并使编写中间件变得更加愉快。
¥A Koa application is an object containing an array of middleware functions
which are composed and executed in a stack-like manner upon request. Koa is similar to many
other middleware systems that you may have encountered such as Ruby's Rack, Connect, and so on -
however a key design decision was made to provide high level "sugar" at the otherwise low-level
middleware layer. This improves interoperability, robustness, and makes writing middleware much
more enjoyable.
这包括用于常见任务的方法,例如内容协商、缓存新鲜度、代理支持和重定向等。尽管提供了相当多的有用方法,Koa 仍然占用很小的空间,因为没有打包任何中间件。
¥This includes methods for common tasks like content-negotiation, cache freshness, proxy support, and redirection
among others. Despite supplying a reasonably large number of helpful methods Koa maintains a small footprint, as
no middleware are bundled.
惯常的 hello world 应用:
¥The obligatory hello world application:
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
app.listen(3000);
¥Cascading
Koa 中间件以更传统的方式级联,就像你可能习惯使用类似的工具一样 - 以前,Node 使用回调很难使用户友好。然而,通过异步函数,我们可以实现 "真" 中间件。对比 Connect 的实现,它只是通过一系列函数传递控制直到一个返回,Koa 调用 "下游",然后控制流回 "上游"。
¥Koa middleware cascade in a more traditional way as you may be used to with similar tools -
this was previously difficult to make user friendly with Node's use of callbacks.
However with async functions we can achieve "true" middleware. Contrasting Connect's implementation which
simply passes control through series of functions until one returns, Koa invoke "downstream", then
control flows back "upstream".
以下示例使用 "Hello World" 进行响应,但请求首先流经
x-response-time
和
logging
中间件以标记请求何时开始,然后通过响应中间件交出控制权。当中间件调用
next()
时,该函数会挂起并将控制权传递给定义的下一个中间件。当下游不再有中间件执行时,堆栈将展开,每个中间件将恢复执行其上游行为。
¥The following example responds with "Hello World", however first the request flows through
the
x-response-time
and
logging
middleware to mark when the request started, then yields control through the response middleware. When a middleware invokes
next()
the function suspends and passes control to the next middleware defined. After there are no more
middleware to execute downstream, the stack will unwind and each middleware is resumed to perform
its upstream behaviour.
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
// response
app.use(async ctx => {
ctx.body = 'Hello World';
app.listen(3000);
¥Settings
应用设置是
app
实例上的属性,目前支持以下内容:
¥Application settings are properties on the
app
instance, currently
the following are supported:
app.env
默认为 NODE_ENV 或 "development"
¥
app.env
defaulting to the
NODE_ENV
or "development"
app.keys
签名 cookie 密钥数组
¥
app.keys
array of signed cookie keys
app.proxy
当为 true 时信任代理标头字段
¥
app.proxy
when true proxy header fields will be trusted
app.subdomainOffset
要忽略的
.subdomains
的偏移量,默认为 2
¥
app.subdomainOffset
offset of
.subdomains
to ignore, default to 2
app.proxyIpHeader
代理 ip 标头,默认为
X-Forwarded-For
¥
app.proxyIpHeader
proxy ip header, default to
X-Forwarded-For
app.maxIpsCount
从代理 ip 标头读取的最大 ip 数,默认为 0(表示无穷大)
¥
app.maxIpsCount
max ips read from proxy ip header, default to 0 (means infinity)
你可以将设置传递给构造函数:
¥You can pass the settings to the constructor:
const Koa = require('koa');
const app = new Koa({ proxy: true });
或动态地:
¥or dynamically:
const Koa = require('koa');
const app = new Koa();
app.proxy = true;
app.listen(...)
Koa 应用不是 HTTP 服务器的一对一表示。一个或多个 Koa 应用可以挂载在一起,以使用单个 HTTP 服务器形成更大的应用。
¥A Koa application is not a 1-to-1 representation of an HTTP server.
One or more Koa applications may be mounted together to form larger
applications with a single HTTP server.
创建并返回一个 HTTP 服务器,将给定参数传递给
Server#listen()
。这些参数记录在
nodejs.org
上。以下是绑定到
3000
端口的无用 Koa 应用:
¥Create and return an HTTP server, passing the given arguments to
Server#listen()
. These arguments are documented on
nodejs.org
. The following is a useless Koa application bound to port
3000
:
const Koa = require('koa');
const app = new Koa();
app.listen(3000);
app.listen(...)
方法只是以下内容的语法糖:
¥The
app.listen(...)
method is simply sugar for the following:
const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
这意味着你可以将同一个应用启动为 HTTP 和 HTTPS,或者在多个地址上启动:
¥This means you can spin up the same application as both HTTP and HTTPS
or on multiple addresses:
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);
app.callback()
返回适合
http.createServer()
方法处理请求的回调函数。你还可以使用此回调函数将你的 Koa 应用挂载到 Connect/Express 应用中。
¥Return a callback function suitable for the
http.createServer()
method to handle a request.
You may also use this callback function to mount your Koa app in a
Connect/Express app.
app.use(function)
将给定的中间件函数添加到该应用。
app.use()
返回
this
,因此是可链式的。
¥Add the given middleware function to this application.
app.use()
returns
this
, so is chainable.
app.use(someMiddleware)
app.use(someOtherMiddleware)
app.listen(3000)
是相同的
¥Is the same as
app.use(someMiddleware)
.use(someOtherMiddleware)
.listen(3000)
请参阅
中间件
了解更多信息。
¥See
Middleware
for
more information.
app.keys=
设置签名的 cookie 密钥。
¥Set signed cookie keys.
这些将传递给
KeyGrip
,但是你也可以传递你自己的
KeyGrip
实例。例如,以下内容是可以接受的:
¥These are passed to
KeyGrip
,
however you may also pass your own
KeyGrip
instance. For
example the following are acceptable:
app.keys = ['OEK5zjaAMPc3L6iK7PyUjCOziUH3rsrMKB9u8H07La1SkfwtuBoDnHaaPCkG5Brg', 'MNKeIebviQnCPo38ufHcSfw3FFv8EtnAe1xE02xkN1wkCV1B2z126U44yk2BQVK7'];
app.keys = new KeyGrip(['OEK5zjaAMPc3L6iK7PyUjCOziUH3rsrMKB9u8H07La1SkfwtuBoDnHaaPCkG5Brg', 'MNKeIebviQnCPo38ufHcSfw3FFv8EtnAe1xE02xkN1wkCV1B2z126U44yk2BQVK7'], 'sha256');
出于安全考虑,请确保密钥足够长且随机。
¥For security reasons, please ensure that the key is long enough and random.
这些密钥可以轮换,并在使用
{ signed: true }
选项签署 cookie 时使用:
¥These keys may be rotated and are used when signing cookies
with the
{ signed: true }
option:
ctx.cookies.set('name', 'tobi', { signed: true });
app.context
app.context
是创建
ctx
的原型。你可以通过编辑
app.context
向
ctx
添加其他属性。这对于向
ctx
添加要在整个应用中使用的属性或方法很有用,这可能会提高性能(无中间件)和/或更容易(更少
require()
),但代价是更多地依赖
ctx
,这可以被视为反模式。
¥
app.context
is the prototype from which
ctx
is created.
You may add additional properties to
ctx
by editing
app.context
.
This is useful for adding properties or methods to
ctx
to be used across your entire app,
which may be more performant (no middleware) and/or easier (fewer
require()
s)
at the expense of relying more on
ctx
, which could be considered an anti-pattern.
例如,要从
ctx
添加对数据库的引用:
¥For example, to add a reference to your database from
ctx
:
app.context.db = db();
app.use(async ctx => {
console.log(ctx.db);
});
注意:
¥Note:
ctx
上的许多属性都是使用 getter、setter 和
Object.defineProperty()
定义的。你只能通过在
app.context
上使用
Object.defineProperty()
来编辑这些属性(不推荐)。参见
https://github.com/koajs/koa/issues/652
。
¥Many properties on
ctx
are defined using getters, setters, and
Object.defineProperty()
. You can only edit these properties (not recommended) by using
Object.defineProperty()
on
app.context
. See
https://github.com/koajs/koa/issues/652
.
已挂载的应用当前使用其父级的
ctx
和设置。因此,挂载的应用实际上只是中间件组。
¥Mounted apps currently use their parent's
ctx
and settings. Thus, mounted apps are really just groups of middleware.
¥Error Handling
默认情况下,除非
app.silent
是
true
,否则将所有错误输出到 stderr。当
err.status
是
404
或
err.expose
是
true
时,默认错误处理程序也不会输出错误。要执行自定义错误处理逻辑(例如集中式日志记录),你可以添加 "error" 事件监听器:
¥By default outputs all errors to stderr unless
app.silent
is
true
.
The default error handler also won't output errors when
err.status
is
404
or
err.expose
is
true
.
To perform custom error-handling logic such as centralized logging you can add an "error" event listener:
app.on('error', err => {
log.error('server error', err)
});
如果 req/res 循环出现错误,无法响应客户端,也会传递
Context
实例:
¥If an error is in the req/res cycle and it is
not
possible to respond to the client, the
Context
instance is also passed:
app.on('error', (err, ctx) => {
log.error('server error', err, ctx)
});
当发生错误并且仍然可以响应客户端时,即没有数据写入套接字时,Koa 将使用 500 "内部服务器错误" 进行适当响应。在任何一种情况下,都会触发应用级别 "error" 以用于记录目的。
¥When an error occurs
and
it is still possible to respond to the client, aka no data has been written to the socket, Koa will respond
appropriately with a 500 "Internal Server Error". In either case
an app-level "error" is emitted for logging purposes.
¥Context
Koa Context 将 Node 的
request
和
response
对象封装到一个对象中,该对象为编写 Web 应用和 API 提供了许多有用的方法。这些操作在 HTTP 服务器开发中使用得非常频繁,因此它们是在此级别添加的,而不是更高级别的框架,这将迫使中间件重新实现此通用功能。
¥A Koa Context encapsulates Node's
request
and
response
objects
into a single object which provides many helpful methods for writing
web applications and APIs.
These operations are used so frequently in HTTP server development
that they are added at this level instead of a higher level framework,
which would force middleware to re-implement this common functionality.
每个请求都会创建一个
Context
,并在中间件中作为接收者或
ctx
标识符进行引用,如以下代码片段所示:
¥A
Context
is created
per
request, and is referenced in middleware
as the receiver, or the
ctx
identifier, as shown in the following
snippet:
app.use(async ctx => {
ctx; // is the Context
ctx.request; // is a Koa Request
ctx.response; // is a Koa Response
});
为了方便起见,许多上下文的访问器和方法只是委托给它们的
ctx.request
或
ctx.response
等效项,并且在其他方面是相同的。例如,
ctx.type
和
ctx.length
委托给
response
对象,
ctx.path
和
ctx.method
委托给
request
。
¥Many of the context's accessors and methods simply delegate to their
ctx.request
or
ctx.response
equivalents for convenience, and are otherwise identical. For example
ctx.type
and
ctx.length
delegate to the
response
object, and
ctx.path
and
ctx.method
delegate to the
request
.
Context
特定方法和访问器。
¥
Context
specific methods and accessors.
ctx.req
节点的
request
对象。
¥Node's
request
object.
ctx.res
节点的
response
对象。
¥Node's
response
object.
不支持绕过 Koa 的响应处理。避免使用以下节点属性:
¥Bypassing Koa's response handling is
not supported
. Avoid using the following Node properties:
res.statusCode
res.writeHead()
res.write()
res.end()
ctx.request
一个 Koa
Request
对象。
¥A Koa
Request
object.
ctx.response
一个 Koa
Response
对象。
¥A Koa
Response
object.
ctx.state
推荐的命名空间,用于通过中间件传递信息并将信息传递到前端视图。
¥The recommended namespace for passing information through middleware and to your frontend views.
ctx.state.user = await User.find(id);
ctx.app
应用实例参考。
¥Application instance reference.
ctx.app.emit
Koa 应用扩展了内部
EventEmitter
。
ctx.app.emit
触发一个事件,其类型由第一个参数定义。对于每个事件,你可以连接 "listeners",这是在事件触发时调用的函数。请参阅
错误处理文档
了解更多信息。
¥Koa applications extend an internal
EventEmitter
.
ctx.app.emit
emits an event with a type, defined by the first argument. For each event you can hook up "listeners", which is a function that is called when the event is emitted. Consult the
error handling docs
for more information.
ctx.cookies.get(name, [options])
获取 cookie
name
和
options
:
¥Get cookie
name
with
options
:
signed
请求的 cookie 应该被签名
¥
signed
the cookie requested should be signed
Koa 使用
cookies
模块,其中选项被简单地传递。
¥Koa uses the
cookies
module where options are simply passed.
ctx.cookies.set(name, value, [options])
将 cookie
name
设置为
value
和
options
:
¥Set cookie
name
to
value
with
options
:
maxAge
:一个数字,表示从
Date.now()
到到期的毫秒数。
¥
maxAge
: a number representing the milliseconds from
Date.now()
for expiry.
expires
:一个
Date
对象,指示 cookie 的到期日期(默认在会话结束时到期)。
¥
expires
: a
Date
object indicating the cookie's expiration date (expires at the end of session by default).
path
:指示 cookie 路径的字符串(默认为
/
)。
¥
path
: a string indicating the path of the cookie (
/
by default).
domain
:指示 cookie 域的字符串(无默认值)。
¥
domain
: a string indicating the domain of the cookie (no default).
secure
:一个布尔值,指示 cookie 是否仅通过 HTTPS 发送(HTTP 默认为
false
,HTTPS 默认为
true
)。
阅读有关此选项的更多信息
。
¥
secure
: a boolean indicating whether the cookie is only to be sent over HTTPS (
false
by default for HTTP,
true
by default for HTTPS).
Read more about this option
.
httpOnly
:一个布尔值,指示 cookie 是否仅通过 HTTP(S) 发送,而不可供客户端 JavaScript 使用(默认为
true
)。
¥
httpOnly
: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (
true
by default).
partitioned
:一个布尔值,表示是否在 Chrome 中为
CHIPS 更新
(默认为
false
)对 cookie 进行分区。如果这是真的,来自嵌入式网站的 Cookie 将被分区,并且只能从创建它的同一顶层网站读取。
¥
partitioned
: a boolean indicating whether to partition the cookie in Chrome for the
CHIPS Update
(
false
by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created.
priority
:一个字符串,表示 cookie 优先级。这可以设置为
'low'
、
'medium'
或
'high'
。
¥
priority
: a string indicating the cookie priority. This can be set to
'low'
,
'medium'
, or
'high'
.
sameSite
:一个布尔值或字符串,指示 cookie 是否为 "同一站点" cookie(默认为
false
)。可以将其设置为
'strict'
、
'lax'
、
'none'
或
true
(映射到
'strict'
)。
¥
sameSite
: a boolean or string indicating whether the cookie is a "same site" cookie (
false
by default). This can be set to
'strict'
,
'lax'
,
'none'
, or
true
(which maps to
'strict'
).
signed
:一个布尔值,指示 cookie 是否要签名(默认为
false
)。如果这是 true,则还将发送附加有
.sig
后缀的另一个同名 cookie,其中包含 27 字节 url 安全的 Base64 SHA1 值,表示 cookie-name=cookie-value 与第一个
要点
密钥的哈希值。该签名密钥用于在下次接收到 cookie 时检测篡改情况。
¥
signed
: a boolean indicating whether the cookie is to be signed (
false
by default). If this is true, another cookie of the same name with the
.sig
suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of
cookie-name
=
cookie-value
against the first
Keygrip
key. This signature key is used to detect tampering the next time a cookie is received.
overwrite
:一个布尔值,指示是否覆盖先前设置的同名 cookie(默认为
false
)。如果这是 true,则在设置此 cookie 时,在同一请求期间设置的具有相同名称(无论路径或域)的所有 cookie 都会从 Set-Cookie 标头中过滤掉。
¥
overwrite
: a boolean indicating whether to overwrite previously set cookies of the same name (
false
by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.
Koa 使用
cookies
模块,其中选项被简单地传递。
¥Koa uses the
cookies
module where options are simply passed.
ctx.throw([status], [msg], [properties])
Helper 方法抛出一个错误,
.status
属性默认为
500
,这将允许 Koa 做出适当的响应。允许以下组合:
¥Helper method to throw an error with a
.status
property
defaulting to
500
that will allow Koa to respond appropriately.
The following combinations are allowed:
ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });
例如
ctx.throw(400, 'name required')
相当于:
¥For example
ctx.throw(400, 'name required')
is equivalent to:
const err = new Error('name required');
err.status = 400;
err.expose = true;
throw err;
请注意,这些是用户级错误,并用
err.expose
标记,这意味着这些消息适合客户端响应,但错误消息通常不是这种情况,因为你不想泄漏故障详细信息。
¥Note that these are user-level errors and are flagged with
err.expose
meaning the messages are appropriate for
client responses, which is typically not the case for
error messages since you do not want to leak failure
details.
你可以选择传递一个按原样合并到错误中的
properties
对象,这对于装饰向上游请求者报告的机器友好错误很有用。
¥You may optionally pass a
properties
object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.
ctx.throw(401, 'access_denied', { user: user });
Koa 使用
http-errors
来创建错误。
status
只能作为第一个参数传递。
¥Koa uses
http-errors
to create errors.
status
should only be passed as the first parameter.
ctx.assert(value, [status], [msg], [properties])
Helper 方法在
!value
时抛出类似于
.throw()
的错误。类似于 Node 的
assert()
方法。
¥Helper method to throw an error similar to
.throw()
when
!value
. Similar to Node's
assert()
method.
ctx.assert(ctx.state.user, 401, 'User not found. Please login!');
Koa 使用
http-assert
进行断言。
¥Koa uses
http-assert
for assertions.
ctx.respond
要绕过 Koa 的内置响应处理,你可以显式设置
ctx.respond = false;
。如果你想写入原始
res
对象而不是让 Koa 为你处理响应,请使用此选项。
¥To bypass Koa's built-in response handling, you may explicitly set
ctx.respond = false;
. Use this if you want to write to the raw
res
object instead of letting Koa handle the response for you.
请注意,Koa 不支持使用此功能。这可能会破坏 Koa 中间件和 Koa 本身的预期功能。使用此属性被认为是一种 hack,并且只是为那些希望在 Koa 中使用传统
fn(req, res)
功能和中间件的人提供便利。
¥Note that using this is
not
supported by Koa. This may break intended functionality of Koa middleware and Koa itself. Using this property is considered a hack and is only a convenience to those wishing to use traditional
fn(req, res)
functions and middleware within Koa.
¥Request aliases
以下访问器和别名
请求
等效项:
¥The following accessors and alias
Request
equivalents:
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()
¥Response aliases
以下访问器和别名
响应
等效项:
¥The following accessors and alias
Response
equivalents:
ctx.body
ctx.body=
ctx.has()
ctx.status
ctx.status=
ctx.message
ctx.message=
ctx.length=
ctx.length
ctx.type=
ctx.type
ctx.vary()
ctx.headerSent
ctx.redirect()
ctx.attachment()
ctx.set()
ctx.append()
ctx.remove()
ctx.lastModified=
ctx.etag=
ctx.writable
¥Request
Koa
Request
对象是 Node 的普通请求对象之上的抽象,提供对日常 HTTP 服务器开发有用的附加功能。
¥A Koa
Request
object is an abstraction on top of Node's vanilla request object,
providing additional functionality that is useful for every day HTTP server
development.
请求标头对象。这与节点的
http.IncomingMessage
上的
headers
字段相同。
¥Request header object. This is the same as the
headers
field
on Node's
http.IncomingMessage
.
设置请求头对象。
¥Set request header object.
请求标头对象。别名为
request.header
。
¥Request header object. Alias as
request.header
.
设置请求头对象。别名为
request.header=
。
¥Set request header object. Alias as
request.header=
.
request.method
请求方法。
¥Request method.
request.method=
设置请求方法,对于实现
methodOverride()
等中间件很有用。
¥Set request method, useful for implementing middleware
such as
methodOverride()
.
request.length
将请求内容长度返回为数字(如果存在)或
undefined
。
¥Return request Content-Length as a number when present, or
undefined
.
request.url
获取请求 URL。
¥Get request URL.
request.url=
设置请求 URL,对于 url 重写很有用。
¥Set request URL, useful for url rewrites.
request.originalUrl
获取请求原始 URL。
¥Get request original URL.
request.origin
获取 URL 的来源,包括
protocol
和
host
。
¥Get origin of URL, include
protocol
and
host
.
ctx.request.origin
// => http://example.com
request.href
获取完整的请求 URL,包括
protocol
、
host
和
url
。
¥Get full request URL, include
protocol
,
host
and
url
.
ctx.request.href;
// => http://example.com/foo/bar?q=1
request.path
获取请求路径名。
¥Get request pathname.
request.path=
设置请求路径名并保留查询字符串(如果存在)。
¥Set request pathname and retain query-string when present.
request.querystring
获取不含
?
的原始查询字符串。
¥Get raw query string void of
?
.
request.querystring=
设置原始查询字符串。
¥Set raw query string.
request.search
使用
?
获取原始查询字符串。
¥Get raw query string with the
?
.
request.search=
设置原始查询字符串。
¥Set raw query string.
request.host
获取主机(主机名:端口)(如果存在)。当
app.proxy
为真时支持
X-Forwarded-Host
,否则使用
Host
。
¥Get host (hostname:port) when present. Supports
X-Forwarded-Host
when
app.proxy
is
true
, otherwise
Host
is used.
request.hostname
获取主机名(如果存在)。当
app.proxy
为真时支持
X-Forwarded-Host
,否则使用
Host
。
¥Get hostname when present. Supports
X-Forwarded-Host
when
app.proxy
is
true
, otherwise
Host
is used.
如果 host 是 IPv6,Koa 将解析委托给
WHATWG URL API
,注意这可能会影响性能。
¥If host is IPv6, Koa delegates parsing to
WHATWG URL API
,
Note
This may impact performance.
request.URL
获取 WHATWG 解析的 URL 对象。
¥Get WHATWG parsed URL object.
request.type
获取请求
Content-Type
不含 "charset" 等参数。
¥Get request
Content-Type
void of parameters such as "charset".
const ct = ctx.request.type;
// => "image/png"
request.charset
获取请求字符集(如果存在)或
undefined
:
¥Get request charset when present, or
undefined
:
ctx.request.charset;
// => "utf-8"
request.query
获取解析的查询字符串,当不存在查询字符串时返回空对象。请注意,此 getter 不支持嵌套解析。
¥Get parsed query-string, returning an empty object when no
query-string is present. Note that this getter does
not
support nested parsing.
例如 "color=blue&size=small":
¥For example "color=blue&size=small":
color: 'blue',
size: 'small'
request.query=
将查询字符串设置为给定对象。请注意,此设置器不支持嵌套对象。
¥Set query-string to the given object. Note that this
setter does
not
support nested objects.
ctx.query = { next: '/login' };
request.fresh
检查请求缓存是否为 "fresh",即内容未更改。该方法用于
If-None-Match
/
ETag
、
If-Modified-Since
、
Last-Modified
之间的缓存协商。应在设置其中一个或多个响应标头后引用它。
¥Check if a request cache is "fresh", aka the contents have not changed. This
method is for cache negotiation between
If-None-Match
/
ETag
, and
If-Modified-Since
and
Last-Modified
. It should be referenced after setting one or more of these response headers.
// freshness check requires status 20x or 304
ctx.status = 200;
ctx.set('ETag', '123');
// cache is ok
if (ctx.fresh) {
ctx.status = 304;
return;
// cache is stale
// fetch new data
ctx.body = await db.find('something');
request.stale
request.fresh
的倒数。
¥Inverse of
request.fresh
.
request.protocol
返回请求协议,"https" 或 "http"。当
app.proxy
为真时支持
X-Forwarded-Proto
。
¥Return request protocol, "https" or "http". Supports
X-Forwarded-Proto
when
app.proxy
is
true
.
request.secure
ctx.protocol == "https"
的简写,用于检查请求是否通过 TLS 发送。
¥Shorthand for
ctx.protocol == "https"
to check if a request was
issued via TLS.
request.ip
请求远程地址。当
app.proxy
为真时支持
X-Forwarded-For
。
¥Request remote address. Supports
X-Forwarded-For
when
app.proxy
is
true
.
request.ips
当
X-Forwarded-For
存在并且
app.proxy
启用时,将返回这些 ip 的数组,按从上游 -> 下游的顺序排列。禁用时返回空数组。
¥When
X-Forwarded-For
is present and
app.proxy
is enabled an array
of these ips is returned, ordered from upstream -> downstream. When
disabled an empty array is returned.
例如,如果值为 "客户端、代理 1、代理 2",你将收到数组
["client", "proxy1", "proxy2"]
。
¥For example if the value were "client, proxy1, proxy2",
you would receive the array
["client", "proxy1", "proxy2"]
.
大多数反向代理(nginx)通过
proxy_add_x_forwarded_for
设置 x-forwarded-for,存在一定的安全风险。恶意攻击者可以通过伪造
X-Forwarded-For
request 标头来伪造客户端的 IP 地址。客户端发送的请求有一个
X-Forwarded-For
的请求头为 'forged'。经过反向代理转发后,
request.ips
将是 ['forged','client','proxy1','proxy2']。
¥Most of the reverse proxy(nginx) set x-forwarded-for via
proxy_add_x_forwarded_for
, which poses a certain security risk.
A malicious attacker can forge a client's ip address by forging
a
X-Forwarded-For
request header. The request sent by the client
has an
X-Forwarded-For
request header for 'forged'. After being
forwarded by the reverse proxy,
request.ips
will be
['forged', 'client', 'proxy1', 'proxy2'].
Koa 提供了两种避免被绕过的选项。
¥Koa offers two options to avoid being bypassed.
如果可以控制反向代理,可以通过调整配置来避免绕过,或者使用 koa 提供的
app.proxyIpHeader
来避免读取
x-forwarded-for
来获取 ips。
¥If you can control the reverse proxy, you can avoid bypassing
by adjusting the configuration, or use the
app.proxyIpHeader
provided by koa to avoid reading
x-forwarded-for
to get ips.
const app = new Koa({
proxy: true,
proxyIpHeader: 'X-Real-IP',
});
如果你确切知道服务器前面有多少个反向代理,你可以通过配置
app.maxIpsCount
来避免读取用户伪造的请求头:
¥If you know exactly how many reverse proxies are in front of
the server, you can avoid reading the user's forged request
header by configuring
app.maxIpsCount
:
const app = new Koa({
proxy: true,
maxIpsCount: 1, // only one proxy in front of the server
// request.header['X-Forwarded-For'] === [ '127.0.0.1', '127.0.0.2' ];
// ctx.ips === [ '127.0.0.2' ];
request.subdomains
以数组形式返回子域。
¥Return subdomains as an array.
子域是应用主域之前主机的以点分隔的部分。默认情况下,应用的域被假定为主机的最后两个部分。这可以通过设置
app.subdomainOffset
来更改。
¥Subdomains are the dot-separated parts of the host before the main domain of
the app. By default, the domain of the app is assumed to be the last two
parts of the host. This can be changed by setting
app.subdomainOffset
.
例如,如果域是 "tobi.ferrets.example.com":如果未设置
app.subdomainOffset
,则
ctx.subdomains
为
["ferrets", "tobi"]
。如果
app.subdomainOffset
为 3,则
ctx.subdomains
为
["tobi"]
。
¥For example, if the domain is "tobi.ferrets.example.com":
If
app.subdomainOffset
is not set,
ctx.subdomains
is
["ferrets", "tobi"]
.
If
app.subdomainOffset
is 3,
ctx.subdomains
is
["tobi"]
.
request.is(types...)
检查传入请求是否包含 "Content-Type" 标头字段,以及是否包含任何给定的 mime
type
。如果没有请求体,则返回
null
。如果没有内容类型,或者匹配失败,则返回
false
。否则,它返回匹配的内容类型。
¥Check if the incoming request contains the "Content-Type"
header field, and it contains any of the give mime
type
s.
If there is no request body,
null
is returned.
If there is no content type, or the match fails
false
is returned.
Otherwise, it returns the matching content-type.
// With Content-Type: text/html; charset=utf-8
ctx.is('html'); // => 'html'
ctx.is('text/html'); // => 'text/html'
ctx.is('text/*', 'text/html'); // => 'text/html'
// When Content-Type is application/json
ctx.is('json', 'urlencoded'); // => 'json'
ctx.is('application/json'); // => 'application/json'
ctx.is('html', 'application/*'); // => 'application/json'
ctx.is('html'); // => false
例如,如果你想确保仅将图片发送到给定路由:
¥For example if you want to ensure that
only images are sent to a given route:
if (ctx.is('image/*')) {
// process
} else {
ctx.throw(415, 'images only!');
¥Content Negotiation
Koa 的 request
对象包括由 accepts 和 negotiator 提供支持的有用的内容协商实用程序。这些实用程序是:
¥Koa's request
object includes helpful content negotiation utilities powered by accepts and negotiator. These utilities are:
request.accepts(types)
request.acceptsEncodings(types)
request.acceptsCharsets(charsets)
request.acceptsLanguages(langs)
如果未提供类型,则返回所有可接受的类型。
¥If no types are supplied, all acceptable types are returned.
如果提供多种类型,将返回最佳匹配。如果未找到匹配项,则返回 false
,并且你应该向客户端发送 406 "Not Acceptable"
响应。
¥If multiple types are supplied, the best match will be returned. If no matches are found, a false
is returned, and you should send a 406 "Not Acceptable"
response to the client.
如果缺少可接受任何类型的接受标头,则将返回第一个类型。因此,你提供的类型的顺序很重要。
¥In the case of missing accept headers where any type is acceptable, the first type will be returned. Thus, the order of types you supply is important.
request.accepts(types)
检查给定的 type(s)
是否可接受,为 true 时返回最佳匹配,否则返回 false
。type
值可以是一个或多个 mime 类型字符串(例如 "application/json")、扩展名(例如 "json")或数组 ["json", "html", "text/plain"]
。
¥Check if the given type(s)
is acceptable, returning the best match when true, otherwise false
. The type
value may be one or more mime type string
such as "application/json", the extension name
such as "json", or an array ["json", "html", "text/plain"]
.
// Accept: text/html
ctx.accepts('html');
// => "html"
// Accept: text/*, application/json
ctx.accepts('html');
// => "html"
ctx.accepts('text/html');
// => "text/html"
ctx.accepts('json', 'text');
// => "json"
ctx.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
ctx.accepts('image/png');
ctx.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
ctx.accepts(['html', 'json']);
ctx.accepts('html', 'json');
// => "json"
// No Accept header
ctx.accepts('html', 'json');
// => "html"
ctx.accepts('json', 'html');
// => "json"
你可以根据需要多次调用 ctx.accepts()
,或者使用开关:
¥You may call ctx.accepts()
as many times as you like,
or use a switch:
switch (ctx.accepts('json', 'html', 'text')) {
case 'json': break;
case 'html': break;
case 'text': break;
default: ctx.throw(406, 'json, html, or text only');
request.acceptsEncodings(encodings)
检查 encodings
是否可接受,为真时返回最佳匹配,否则返回 false
。请注意,你应该包含 identity
作为编码之一!
¥Check if encodings
are acceptable, returning the best match when true, otherwise false
. Note that you should include identity
as one of the encodings!
// Accept-Encoding: gzip
ctx.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"
ctx.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"
当没有给出参数时,所有接受的编码都作为数组返回:
¥When no arguments are given all accepted encodings
are returned as an array:
// Accept-Encoding: gzip, deflate
ctx.acceptsEncodings();
// => ["gzip", "deflate", "identity"]
请注意,如果客户端显式发送 identity;q=0
,则 identity
编码(意味着无编码)可能不可接受。尽管这是一种边缘情况,但你仍然应该处理此方法返回 false
的情况。
¥Note that the identity
encoding (which means no encoding) could be unacceptable if the client explicitly sends identity;q=0
. Although this is an edge case, you should still handle the case where this method returns false
.
request.acceptsCharsets(charsets)
检查 charsets
是否可接受,为真时返回最佳匹配,否则返回 false
。
¥Check if charsets
are acceptable, returning
the best match when true, otherwise false
.
// 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"
当没有给出参数时,所有接受的字符集都作为数组返回:
¥When no arguments are given all accepted charsets
are returned as an array:
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]
request.acceptsLanguages(langs)
检查 langs
是否可接受,为真时返回最佳匹配,否则返回 false
。
¥Check if langs
are acceptable, returning
the best match when true, otherwise false
.
// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages('es', 'en');
// => "es"
ctx.acceptsLanguages(['en', 'es']);
// => "es"
当没有给出参数时,所有接受的语言都作为数组返回:
¥When no arguments are given all accepted languages
are returned as an array:
// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages();
// => ["es", "pt", "en"]
request.idempotent
检查请求是否幂等。
¥Check if the request is idempotent.
request.socket
返回请求套接字。
¥Return the request socket.
request.get(field)
返回请求头,不区分大小写 field
。
¥Return request header with case-insensitive field
.
¥Response
Koa Response
对象是 Node 的普通响应对象之上的抽象,提供对日常 HTTP 服务器开发有用的附加功能。
¥A Koa Response
object is an abstraction on top of Node's vanilla response object,
providing additional functionality that is useful for every day HTTP server
development.
响应头对象。
¥Response header object.
响应头对象。别名为 response.header
。
¥Response header object. Alias as response.header
.
response.socket
响应套接字。指向 request.socket
的 net.Socket 实例。
¥Response socket. Points to net.Socket instance as request.socket
.
response.status
获取响应状态。默认情况下,response.status
设置为 404
,与 Node 的 res.statusCode
默认设置为 200
不同。
¥Get response status. By default, response.status
is set to 404
unlike Node's res.statusCode
which defaults to 200
.
response.status=
通过数字代码设置响应状态:
¥Set response status via numeric code:
100 "继续"
¥100 "continue"
101 "切换协议"
¥101 "switching protocols"
102 "处理中"
¥102 "processing"
200 "ok"
201 "已创建"
¥201 "created"
202 "已接受"
¥202 "accepted"
203 "非权威信息"
¥203 "non-authoritative information"
204 "无内容"
¥204 "no content"
205 "重置内容"
¥205 "reset content"
206 "部分内容"
¥206 "partial content"
207 "多状态"
¥207 "multi-status"
208 "已上报"
¥208 "already reported"
226 "已使用"
¥226 "im used"
300 "多项选择"
¥300 "multiple choices"
301 "永久移动"
¥301 "moved permanently"
302 "已找到"
¥302 "found"
303 "查看其他"
¥303 "see other"
304 "未修改"
¥304 "not modified"
305 "使用代理服务器"
¥305 "use proxy"
307 "临时重定向"
¥307 "temporary redirect"
308 "永久重定向"
¥308 "permanent redirect"
400 "错误的请求"
¥400 "bad request"
401 "未授权"
¥401 "unauthorized"
402 "需要付款"
¥402 "payment required"
403 "已禁止"
¥403 "forbidden"
404 "未找到"
¥404 "not found"
405 "方法不允许"
¥405 "method not allowed"
406 "不被接受的"
¥406 "not acceptable"
407 "需要代理身份验证"
¥407 "proxy authentication required"
408 "请求超时"
¥408 "request timeout"
409 "冲突"
¥409 "conflict"
410 "已失去"
¥410 "gone"
411 "需要长度"
¥411 "length required"
412 "前提条件失败"
¥412 "precondition failed"
413 "有效载荷太大"
¥413 "payload too large"
414 "uri 太长"
¥414 "uri too long"
415 "不支持的媒体类型"
¥415 "unsupported media type"
416 "范围不满足"
¥416 "range not satisfiable"
417 "期望失败"
¥417 "expectation failed"
418 "我是茶壶"
¥418 "I'm a teapot"
422 "不可处理的实体"
¥422 "unprocessable entity"
423 "已上锁"
¥423 "locked"
424 "失败的依赖"
¥424 "failed dependency"
426 "需要升级"
¥426 "upgrade required"
428 "需要先决条件"
¥428 "precondition required"
429 "请求太多"
¥429 "too many requests"
431 "请求头字段太大"
¥431 "request header fields too large"
500 "内部服务器错误"
¥500 "internal server error"
501 "未实现"
¥501 "not implemented"
502 "错误的网关"
¥502 "bad gateway"
503 "暂停服务"
¥503 "service unavailable"
504 "网关超时"
¥504 "gateway timeout"
505 "不支持 http 版本"
¥505 "http version not supported"
506 "变体也协商"
¥506 "variant also negotiates"
507 "存储空间不足"
¥507 "insufficient storage"
508 "检测到循环"
¥508 "loop detected"
510 "未扩展"
¥510 "not extended"
511 "需要网络认证"
¥511 "network authentication required"
注意:不要太担心记住这些字符串,如果你有拼写错误,将会抛出错误,显示此列表以便你可以进行更正。
¥NOTE: don't worry too much about memorizing these strings,
if you have a typo an error will be thrown, displaying this list
so you can make a correction.
由于 response.status
默认设置为 404
,因此要发送不带正文且具有不同状态的响应,请按如下方式完成:
¥Since response.status
default is set to 404
, to send a response
without a body and with a different status is to be done like this:
ctx.response.status = 200;
// Or whatever other status
ctx.response.status = 204;
response.message
获取响应状态消息。默认情况下,response.message
与 response.status
关联。
¥Get response status message. By default, response.message
is
associated with response.status
.
response.message=
将响应状态消息设置为给定值。
¥Set response status message to the given value.
response.length=
将响应内容长度设置为给定值。
¥Set response Content-Length to the given value.
response.length
如果存在,则以数字形式返回响应内容长度,或者在可能的情况下从 ctx.body
或 undefined
中推导出来。
¥Return response Content-Length as a number when present, or deduce
from ctx.body
when possible, or undefined
.
response.body
获取响应正文。
¥Get response body.
response.body=
将响应正文设置为以下内容之一:
¥Set response body to one of the following:
string
已写
¥string
written
Buffer
已写
¥Buffer
written
Stream
管道式
¥Stream
piped
Object
|| Array
json-stringified
null
|| undefined
无内容响应
¥null
|| undefined
no content response
如果没有设置 response.status
,Koa 会根据 response.body
自动将状态设置为 200
或 204
。具体来说,如果 response.body
没有设置或者已经设置为 null
或 undefined
,Koa 会自动将 response.status
设置为 204
。如果你确实想发送其他状态的无内容响应,则应按以下方式覆盖 204
状态:
¥If response.status
has not been set, Koa will automatically set the status to 200
or 204
depending on response.body
. Specifically, if response.body
has not been set or has been set as null
or undefined
, Koa will automatically set response.status
to 204
. If you really want to send no content response with other status, you should override the 204
status as the following way:
// This must be always set first before status, since null | undefined
// body automatically sets the status to 204
ctx.body = null;
// Now we override the 204 status with the desired one
ctx.status = 200;
Koa 并不防范所有可以作为响应主体的内容 - 函数没有有意义的序列化,根据你的应用返回一个布尔值可能有意义,并且虽然错误有效,但它可能不会像某些人预期的那样工作 错误的属性是不可枚举的。我们建议在你的应用中添加中间件来断言每个应用的正文类型。示例中间件可能是:
¥Koa doesn't guard against everything that could be put as a response body -- a function doesn't serialise meaningfully, returning a boolean may make sense based on your application, and while an error works, it may not work as intended as some properties of an error are not enumerable. We recommend adding middleware in your app that asserts body types per app. A sample middleware might be:
app.use(async (ctx, next) => {
await next()
ctx.assert.equal('object', typeof ctx.body, 500, 'some dev did something wrong')
¥String
Content-Type 默认为 text/html 或 text/plain,两者的默认字符集均为 utf-8。还设置了内容长度字段。
¥The Content-Type is defaulted to text/html or text/plain, both with
a default charset of utf-8. The Content-Length field is also set.
¥Buffer
Content-Type 默认为 application/octet-stream,并且还设置了 Content-Length。
¥The Content-Type is defaulted to application/octet-stream, and Content-Length
is also set.
¥Stream
Content-Type 默认为 application/octet-stream。
¥The Content-Type is defaulted to application/octet-stream.
每当将流设置为响应正文时,.onerror
就会自动添加为 error
事件的监听器以捕获任何错误。此外,每当请求关闭(甚至过早)时,流都会被销毁。如果你不需要这两个功能,请不要直接将流设置为正文。例如,当将主体设置为代理中的 HTTP 流时,你可能不希望这样做,因为这会破坏底层连接。
¥Whenever a stream is set as the response body, .onerror
is automatically added as a listener to the error
event to catch any errors.
In addition, whenever the request is closed (even prematurely), the stream is destroyed.
If you do not want these two features, do not set the stream as the body directly.
For example, you may not want this when setting the body as an HTTP stream in a proxy as it would destroy the underlying connection.
看:https://github.com/koajs/koa/pull/612 了解更多信息。
¥See: https://github.com/koajs/koa/pull/612 for more information.
下面是一个在不自动销毁流的情况下进行流错误处理的示例:
¥Here's an example of stream error handling without automatically destroying the stream:
const PassThrough = require('stream').PassThrough;
app.use(async ctx => {
ctx.body = someHTTPStream.on('error', (err) => ctx.onerror(err)).pipe(PassThrough());
¥Object
Content-Type 默认为 application/json。这包括普通对象 { foo: 'bar' }
和数组 ['foo', 'bar']
。
¥The Content-Type is defaulted to application/json. This includes plain objects { foo: 'bar' }
and arrays ['foo', 'bar']
.
response.get(field)
获取响应头字段值,不区分大小写 field
。
¥Get a response header field value with case-insensitive field
.
const etag = ctx.response.get('ETag');
response.has(field)
如果当前在传出标头中设置了由名称标识的标头,则返回 true
。标头名称匹配不区分大小写。
¥Returns true
if the header identified by name is currently set in the outgoing headers.
The header name matching is case-insensitive.
const rateLimited = ctx.response.has('X-RateLimit-Limit');
response.set(field, value)
将响应标头 field
设置为 value
:
¥Set response header field
to value
:
ctx.set('Cache-Control', 'no-cache');
response.append(field, value)
附加带有值 val
的附加标头 field
。
¥Append additional header field
with value val
.
ctx.append('Link', 'http://127.0.0.1');
response.set(fields)
用一个对象设置几个响应头 fields
:
¥Set several response header fields
with an object:
ctx.set({
'Etag': '1234',
'Last-Modified': date
});
这委托给 setHeader,它通过指定的键设置或更新标头,并且不会重置整个标头。
¥This delegates to setHeader which sets or updates headers by specified keys and doesn't reset the entire header.
response.remove(field)
删除标头 field
。
¥Remove header field
.
response.type
获取响应 Content-Type
,不含 "charset" 等参数。
¥Get response Content-Type
void of parameters such as "charset".
const ct = ctx.type;
// => "image/png"
response.type=
通过 mime 字符串或文件扩展名设置响应 Content-Type
。
¥Set response Content-Type
via mime string or file extension.
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')
直接将响应头字段设置为值。
¥Note: when appropriate a charset
is selected for you, for
example response.type = 'html'
will default to "utf-8". If you need to overwrite charset
,
use ctx.set('Content-Type', 'text/html')
to set response header field to value directly.
response.is(types...)
与 ctx.request.is()
非常相似。检查响应类型是否是提供的类型之一。这对于创建操纵响应的中间件特别有用。
¥Very similar to ctx.request.is()
.
Check whether the response type is one of the supplied types.
This is particularly useful for creating middleware that
manipulate responses.
例如,这是一个缩小除流之外的所有 HTML 响应的中间件。
¥For example, this is a middleware that minifies
all HTML responses except for streams.