Skip to main content

请求

请求

¥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 by querystringParser

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

  • params - 与 URL 匹配的参数

    ¥params - the params matching the URL

  • headers - 标头 getter 和 setter

    ¥headers - the headers getter and setter

  • raw - 来自 Node 核心的传入 HTTP 请求

    ¥raw - the incoming HTTP request from Node core

  • server - Fastify 服务器实例,作用域为当前 封装上下文

    ¥server - The Fastify server instance, scoped to the current encapsulation context

  • id - 请求 ID

    ¥id - the request ID

  • log - 传入请求的日志器实例

    ¥log - the logger instance of the incoming request

  • ip - 传入请求的 IP 地址

    ¥ip - the IP address of the incoming request

  • ips - 传入请求的 X-Forwarded-For 标头中的 IP 地址数组,从最近到最远排序(仅当启用 trustProxy 选项时)

    ¥ips - an array of the IP addresses, ordered from closest to furthest, in the X-Forwarded-For header of the incoming request (only when the trustProxy option is enabled)

  • host - 传入请求的主机(启用 trustProxy 选项时从 X-Forwarded-Host 标头派生)。对于 HTTP/2 兼容性,如果不存在主机标头,它将返回 :authority。当你在服务器选项中使用 requireHostHeader = false 时,如果缺少主机标头,它将回退为空。

    ¥host - the host of the incoming request (derived from X-Forwarded-Host header when the trustProxy option is enabled). For HTTP/2 compatibility it returns :authority if no host header exists. When you use requireHostHeader = 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 port

  • port - 服务器正在监听的端口

    ¥port - the port that the server is listening on

  • protocol - 传入请求的协议(httpshttp

    ¥protocol - the protocol of the incoming request (https or http)

  • method - 传入请求的方法

    ¥method - the method of the incoming request

  • url - 传入请求的 URL

    ¥url - the URL of the incoming request

  • originalUrl - 类似于 url,这允许你在内部重新路由的情况下访问原始 url

    ¥originalUrl - similar to url, this allows you to access the original url in case of internal re-routing

  • is404 - 如果请求由 404 处理程序处理,则为 true,否则为 false

    ¥is404 - true if request is being handled by 404 handler, false if it is not

  • socket - 传入请求的底层连接

    ¥socket - the underlying connection of the incoming request

  • context - 已弃用,改用 request.routeOptions.config。Fastify 内部对象。你不应该直接使用它或修改它。访问一个特殊的密钥很有用:

    ¥context - Deprecated, use request.routeOptions.config instead. A Fastify internal object. You should not use it directly or modify it. It is useful to access one special key:

    • context.config - 路由 config 对象。

      ¥context.config - The route config object.

  • routeOptions - 路由 option 对象

    ¥routeOptions - The route option object

    • bodyLimit - 服务器限制或路由限制

      ¥bodyLimit - either server limit or route limit

    • config - 此路由的 config 对象

      ¥config - the config object for this route

    • method - 路由的 http 方法

      ¥method - the http method for the route

    • url - 与此路由匹配的 URL 路径

      ¥url - the path of the URL to match this route

    • handler - 此路由的处理程序

      ¥handler - the handler for this route

    • attachValidation - 将 validationError 附加到请求(如果定义了模式)

      ¥attachValidation - attach validationError to request (if there is a schema defined)

    • logLevel - 为此路由定义的日志级别

      ¥logLevel - log level defined for this route

    • schema - 此路由的 JSON 模式定义

      ¥schema - the JSON schemas definition for this route

    • version - 定义端点版本的 semver 兼容字符串

      ¥version - a semver compatible string that defines the version of the endpoint

    • exposeHeadRoute - 为任何 GET 路由创建同级 HEAD 路由

      ¥exposeHeadRoute - creates a sibling HEAD route for any GET routes

    • prefixTrailingSlash - 用于确定如何处理将 / 作为带有前缀的路由传递的字符串。

      ¥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 optional httpPart is forwarded to the ValidationCompiler if provided, defaults to null.

  • .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 to null.

标头

¥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 property Symbol('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)

通过使用提供的 schemahttpPart 调用此函数,它将返回一个可用于验证不同输入的 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.