请求
请求
¥Request
处理程序函数的第一个参数是 Request
。
¥The first parameter of the handler function is Request
.
Request 是一个核心 Fastify 对象,包含以下字段:
¥Request is a core Fastify object containing the following fields:
query
- 解析的查询字符串,其格式由querystringParser
指定¥
query
- the parsed querystring, its format is specified byquerystringParser
body
- 请求负载,有关 Fastify 原生解析的请求负载以及如何支持其他内容类型的详细信息,请参阅 内容类型解析器¥
body
- the request payload, see Content-Type Parser for details on what request payloads Fastify natively parses and how to support other content typesparams
- 与 URL 匹配的参数¥
params
- the params matching the URLheaders
- 标头 getter 和 setter¥
headers
- the headers getter and setterraw
- 来自 Node 核心的传入 HTTP 请求¥
raw
- the incoming HTTP request from Node coreserver
- Fastify 服务器实例,作用域为当前 封装上下文¥
server
- The Fastify server instance, scoped to the current encapsulation contextid
- 请求 ID¥
id
- the request IDlog
- 传入请求的日志器实例¥
log
- the logger instance of the incoming requestip
- 传入请求的 IP 地址¥
ip
- the IP address of the incoming requestips
- 传入请求的X-Forwarded-For
标头中的 IP 地址数组,从最近到最远排序(仅当启用trustProxy
选项时)¥
ips
- an array of the IP addresses, ordered from closest to furthest, in theX-Forwarded-For
header of the incoming request (only when thetrustProxy
option is enabled)host
- 传入请求的主机(启用trustProxy
选项时从X-Forwarded-Host
标头派生)。对于 HTTP/2 兼容性,如果不存在主机标头,它将返回:authority
。当你在服务器选项中使用requireHostHeader = false
时,如果缺少主机标头,它将回退为空。¥
host
- the host of the incoming request (derived fromX-Forwarded-Host
header when thetrustProxy
option is enabled). For HTTP/2 compatibility it returns:authority
if no host header exists. When you userequireHostHeader = false
in the server options, it will fallback as empty when the host header is missing.hostname
- 传入请求的主机(不带端口)¥
hostname
- the host of the incoming request without the portport
- 服务器正在监听的端口¥
port
- the port that the server is listening onprotocol
- 传入请求的协议(https
或http
)¥
protocol
- the protocol of the incoming request (https
orhttp
)method
- 传入请求的方法¥
method
- the method of the incoming requesturl
- 传入请求的 URL¥
url
- the URL of the incoming requestoriginalUrl
- 类似于url
,这允许你在内部重新路由的情况下访问原始url
¥
originalUrl
- similar tourl
, this allows you to access the originalurl
in case of internal re-routingis404
- 如果请求由 404 处理程序处理,则为 true,否则为 false¥
is404
- true if request is being handled by 404 handler, false if it is notsocket
- 传入请求的底层连接¥
socket
- the underlying connection of the incoming requestcontext
- 已弃用,改用request.routeOptions.config
。Fastify 内部对象。你不应该直接使用它或修改它。访问一个特殊的密钥很有用:¥
context
- Deprecated, userequest.routeOptions.config
instead. A Fastify internal object. You should not use it directly or modify it. It is useful to access one special key:routeOptions
- 路由option
对象¥
routeOptions
- The routeoption
objectbodyLimit
- 服务器限制或路由限制¥
bodyLimit
- either server limit or route limitconfig
- 此路由的config
对象¥
config
- theconfig
object for this routemethod
- 路由的 http 方法¥
method
- the http method for the routeurl
- 与此路由匹配的 URL 路径¥
url
- the path of the URL to match this routehandler
- 此路由的处理程序¥
handler
- the handler for this routeattachValidation
- 将validationError
附加到请求(如果定义了模式)¥
attachValidation
- attachvalidationError
to request (if there is a schema defined)logLevel
- 为此路由定义的日志级别¥
logLevel
- log level defined for this routeschema
- 此路由的 JSON 模式定义¥
schema
- the JSON schemas definition for this routeversion
- 定义端点版本的 semver 兼容字符串¥
version
- a semver compatible string that defines the version of the endpointexposeHeadRoute
- 为任何 GET 路由创建同级 HEAD 路由¥
exposeHeadRoute
- creates a sibling HEAD route for any GET routesprefixTrailingSlash
- 用于确定如何处理将 / 作为带有前缀的路由传递的字符串。¥
prefixTrailingSlash
- string used to determine how to handle passing / as a route with a prefix.
.getValidationFunction(schema | httpPart) - 如果设置或缓存了其中任何一个,则返回指定架构或 http 部分的验证函数。
¥.getValidationFunction(schema | httpPart) - Returns a validation function for the specified schema or http part, if any of either are set or cached.
.compileValidationSchema(schema, [httpPart]) - 使用默认(或自定义)
ValidationCompiler
编译指定的模式并返回验证函数。如果提供可选httpPart
,则转发到ValidationCompiler
,默认为null
。¥.compileValidationSchema(schema, [httpPart]) - Compiles the specified schema and returns a validation function using the default (or customized)
ValidationCompiler
. The optionalhttpPart
is forwarded to theValidationCompiler
if provided, defaults tonull
..validateInput(data, schema | httpPart, [httpPart]) - 使用指定的架构验证指定的输入并返回序列化的有效负载。如果提供了可选的
httpPart
,则该函数将使用为该 HTTP 状态代码提供的序列化器函数。默认为null
。¥.validateInput(data, schema | httpPart, [httpPart]) - Validates the specified input by using the specified schema and returns the serialized payload. If the optional
httpPart
is provided, the function will use the serializer function given for that HTTP Status Code. Defaults tonull
.
标头
¥Headers
request.headers
是一个 getter,它返回一个包含传入请求标头的对象。你可以像这样设置自定义标头:
¥The request.headers
is a getter that returns an Object with the headers of the
incoming request. You can set custom headers like this:
request.headers = {
'foo': 'bar',
'baz': 'qux'
}
此操作将向请求标头添加可通过调用 request.headers.bar
读取的新值。此外,你仍然可以使用 request.raw.headers
属性访问标准请求的标头。
¥This operation will add to the request headers the new values that can be read
calling request.headers.bar
. Moreover, you can still access the standard
request's headers with the request.raw.headers
property.
注意:出于
not found
路由的性能原因,你可能会看到我们将在标题上添加一个额外的属性Symbol('fastify.RequestAcceptVersion')
。¥Note: For performance reason on
not found
route, you may see that we will add an extra propertySymbol('fastify.RequestAcceptVersion')
on the headers.
fastify.post('/:params', options, function (request, reply) {
console.log(request.body)
console.log(request.query)
console.log(request.params)
console.log(request.headers)
console.log(request.raw)
console.log(request.server)
console.log(request.id)
console.log(request.ip)
console.log(request.ips)
console.log(request.host)
console.log(request.hostname)
console.log(request.port)
console.log(request.protocol)
console.log(request.url)
console.log(request.routeOptions.method)
console.log(request.routeOptions.bodyLimit)
console.log(request.routeOptions.method)
console.log(request.routeOptions.url)
console.log(request.routeOptions.attachValidation)
console.log(request.routeOptions.logLevel)
console.log(request.routeOptions.version)
console.log(request.routeOptions.exposeHeadRoute)
console.log(request.routeOptions.prefixTrailingSlash)
console.log(request.routeOptions.logLevel)
request.log.info('some info')
})
.getValidationFunction(schema | httpPart)
通过使用提供的 schema
或 httpPart
调用此函数,它将返回一个可用于验证不同输入的 validation
函数。如果使用提供的输入中的任何一个都找不到序列化函数,则返回 undefined
。
¥By calling this function using a provided schema
or httpPart
,
it will return a validation
function that can be used to
validate diverse inputs. It returns undefined
if no
serialization function was found using either of the provided inputs.
该函数存在属性错误。上次验证期间遇到的错误将分配给错误
¥This function has property errors. Errors encountered during the last validation are assigned to errors
const validate = request
.getValidationFunction({
type: 'object',
properties: {
foo: {
type: 'string'
}
}
})
console.log(validate({ foo: 'bar' })) // true
console.log(validate.errors) // null
// or
const validate = request
.getValidationFunction('body')
console.log(validate({ foo: 0.5 })) // false
console.log(validate.errors) // validation errors
请参阅 .compileValidationSchema(schema, [httpStatus]) 了解有关如何编译验证函数的更多信息。
¥See .compileValidationSchema(schema, [httpStatus]) for more information on how to compile validation function.
.compileValidationSchema(schema, [httpPart])
该函数将编译验证模式并返回可用于验证数据的函数。返回的函数(又名验证函数)是使用提供的 SchemaController#ValidationCompiler
编译的。WeakMap
用于缓存此内容,减少编译调用。
¥This function will compile a validation schema and
return a function that can be used to validate data.
The function returned (a.k.a. validation function) is compiled
by using the provided SchemaController#ValidationCompiler
.
A WeakMap
is used to cached this, reducing compilation calls.
如果提供可选参数 httpPart
,则直接转发到 ValidationCompiler
,因此如果为路由提供了自定义 ValidationCompiler
,则可以使用它来编译验证函数。
¥The optional parameter httpPart
, if provided, is forwarded directly
the ValidationCompiler
, so it can be used to compile the validation
function if a custom ValidationCompiler
is provided for the route.
该函数存在属性错误。上次验证期间遇到的错误将分配给错误
¥This function has property errors. Errors encountered during the last validation are assigned to errors
const validate = request
.compileValidationSchema({
type: 'object',
properties: {
foo: {
type: 'string'
}
}
})
console.log(validate({ foo: 'bar' })) // true
console.log(validate.errors) // null
// or
const validate = request
.compileValidationSchema({
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}, 200)
console.log(validate({ hello: 'world' })) // false
console.log(validate.errors) // validation errors
请注意,使用此函数时应小心,因为它将根据提供的架构缓存已编译的验证函数。如果提供的模式发生修改或更改,验证函数将不会检测到模式已更改,例如,它将重用先前编译的验证函数,因为缓存基于先前提供的模式(对象)的引用。
¥Note that you should be careful when using this function, as it will cache the compiled validation functions based on the schema provided. If the schemas provided are mutated or changed, the validation functions will not detect that the schema has been altered and for instance it will reuse the previously compiled validation function, as the cache is based on the reference of the schema (Object) previously provided.
如果需要更改模式的属性,请始终选择创建全新的模式(对象),否则实现将无法从缓存机制中受益。
¥If there is a need to change the properties of a schema, always opt to create a totally new schema (object), otherwise the implementation will not benefit from the cache mechanism.
使用以下架构作为示例:
¥Using the following schema as an example:
const schema1 = {
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}
不是
¥Not
const validate = request.compileValidationSchema(schema1)
// Later on...
schema1.properties.foo.type. = 'integer'
const newValidate = request.compileValidationSchema(schema1)
console.log(newValidate === validate) // true
反而
¥Instead
const validate = request.compileValidationSchema(schema1)
// Later on...
const newSchema = Object.assign({}, schema1)
newSchema.properties.foo.type = 'integer'
const newValidate = request.compileValidationSchema(newSchema)
console.log(newValidate === validate) // false
.validateInput(data, [schema | httpStatus], [httpStatus])
此函数将根据提供的架构或传递的 HTTP 部分验证输入。如果同时提供,则 httpPart
参数将优先。
¥This function will validate the input based on the provided schema,
or HTTP part passed. If both are provided, the httpPart
parameter
will take precedence.
如果给定的 schema
没有验证函数,则将编译一个新的验证函数,如果提供则转发 httpPart
。
¥If there is not a validation function for a given schema
, a new validation
function will be compiled, forwarding the httpPart
if provided.
request
.validateInput({ foo: 'bar'}, {
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}) // true
// or
request
.validateInput({ foo: 'bar'}, {
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}, 'body') // true
// or
request
.validateInput({ hello: 'world'}, 'query') // false
请参阅 .compileValidationSchema(schema, [httpStatus]) 了解有关如何编译验证模式的更多信息。
¥See .compileValidationSchema(schema, [httpStatus]) for more information on how to compile validation schemas.