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。如果 requireHostHeaderfalse、未提供 HTTP/1.0 或通过架构验证删除,则主机标头可能返回空字符串。

    ¥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. The host header may return an empty string if requireHostHeader is false, not provided with HTTP/1.0, or removed by schema validation.

  • hostname - 从传入请求的 host 属性派生的主机名。

    ¥hostname - The hostname derived from the host property of the incoming request.

  • port - 来自 host 属性的端口,可能指服务器正在监听的端口。

    ¥port - The port from the host property, which may refer to the port 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, allows access to the original url in case of internal re-routing.

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

    ¥is404 - true if request is being handled by 404 handler, false otherwise.

  • 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. Do not use or modify it directly. 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 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 input using the specified schema and returns the serialized payload. If httpPart is provided, the function uses the serializer 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. Set custom headers as follows:

request.headers = {
'foo': 'bar',
'baz': 'qux'
}

此操作将新值添加到可通过 request.headers.bar 访问的请求标头。标准请求标头仍然可通过 request.raw.headers 访问。

¥This operation adds new values to the request headers, accessible via request.headers.bar. Standard request headers remain accessible via request.raw.headers.

出于性能原因,Symbol('fastify.RequestAcceptVersion') 可能会添加到 not found 路由的标头中。

¥For performance reasons, Symbol('fastify.RequestAcceptVersion') may be added to headers on not found routes.

ℹ️ 注意:架构验证可能会改变 request.headersrequest.raw.headers 对象,导致标头变为空。

¥ℹ️ Note: Schema validation may mutate the request.headers and request.raw.headers objects, causing the headers to become empty.

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 with a provided schema or httpPart, it returns a validation function to validate diverse inputs. It returns undefined if no serialization function is found using the provided inputs.

此函数具有 errors 属性。上次验证期间遇到的错误被分配给 errors

¥This function has an errors property. 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 compiling validation schemas.

.compileValidationSchema(schema, [httpPart])

此函数编译验证模式并返回一个函数来验证数据。返回的函数(又名验证函数)是使用提供的 SchemaController#ValidationCompiler 编译的。WeakMap 用于缓存此内容,减少编译调用。

¥This function compiles a validation schema and returns a function to validate data. The returned function (a.k.a. validation function) is compiled using the provided SchemaController#ValidationCompiler. A WeakMap is used to cache this, reducing compilation calls.

如果提供了可选参数 httpPart,则将其转发到 ValidationCompiler,如果为路由提供了自定义 ValidationCompiler,则允许它编译验证函数。

¥The optional parameter httpPart, if provided, is forwarded to the ValidationCompiler, allowing it to compile the validation function if a custom ValidationCompiler is provided for the route.

此函数具有 errors 属性。上次验证期间遇到的错误被分配给 errors

¥This function has an errors property. 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

使用此函数时要小心,因为它会根据提供的模式缓存已编译的验证函数。如果架构发生修改或更改,验证函数将不会检测到更改并将重用先前编译的验证函数,因为缓存基于架构的引用。

¥Be careful when using this function, as it caches compiled validation functions based on the provided schema. If schemas are mutated or changed, the validation functions will not detect the alterations and will reuse the previously compiled validation function, as the cache is based on the schema's reference.

如果需要更改架构属性,请创建一个新的架构对象以从缓存机制中受益。

¥If schema properties need to be changed, create a new schema object to 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 validates the input based on the provided schema or HTTP part. If both are provided, the httpPart parameter takes precedence.

如果给定的 schema 不存在验证函数,则将编译新的验证函数,并转发 httpPart(如果提供)。

¥If no validation function exists 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 compiling validation schemas.