跳至主要内容
版本: 最新版本 (v5.0.x)

请求

请求

处理程序函数的第一个参数是 Request

Request 是一个核心 Fastify 对象,包含以下字段

  • query - 解析后的查询字符串,其格式由 querystringParser 指定
  • body - 请求负载,有关 Fastify 本机解析哪些请求负载以及如何支持其他内容类型的详细信息,请参阅 内容类型解析器
  • params - 与 URL 匹配的参数
  • headers - 标头 getter 和 setter
  • raw - 来自 Node 核心的传入 HTTP 请求
  • server - Fastify 服务器实例,作用域限定为当前的 封装上下文
  • id - 请求 ID
  • log - 传入请求的日志记录器实例
  • ip - 传入请求的 IP 地址
  • ips - IP 地址数组,按从近到远的顺序排列,位于传入请求的 X-Forwarded-For 标头中(仅当 trustProxy 选项启用时)
  • host - 传入请求的主机(当 trustProxy 选项启用时,从 X-Forwarded-Host 标头派生)。为了与 HTTP/2 兼容,如果不存在主机标头,则返回 :authority
  • hostname - 传入请求的主机,不包含端口
  • port - 服务器正在侦听的端口
  • protocol - 传入请求的协议(httpshttp
  • method - 传入请求的方法
  • url - 传入请求的 URL
  • originalUrl - 与 url 类似,这允许您在内部重新路由的情况下访问原始 url
  • is404 - 如果请求由 404 处理程序处理,则为 true,否则为 false
  • socket - 传入请求的基础连接
  • context - 已弃用,请改用 request.routeOptions.config。Fastify 内部对象。您不应该直接使用或修改它。它用于访问一个特殊的键
    • context.config - 路由 config 对象。
  • routeOptions - 路由 option 对象
    • bodyLimit - 服务器限制或路由限制
    • config - 此路由的 config 对象
    • method - 路由的 HTTP 方法
    • url - 与此路由匹配的 URL 路径
    • handler - 此路由的处理程序
    • attachValidation - 将 validationError 附加到请求(如果定义了模式)
    • logLevel - 为此路由定义的日志级别
    • schema - 此路由的 JSON 模式定义
    • version - 定义端点版本的与语义版本兼容的字符串
    • exposeHeadRoute - 为任何 GET 路由创建同级 HEAD 路由。
    • prefixTrailingSlash - 用于确定如何处理将 / 作为带有前缀的路由传递的字符串。
  • .getValidationFunction(schema | httpPart) - 返回指定模式或 HTTP 部分的验证函数(如果设置或缓存了其中任何一个)。
  • .compileValidationSchema(schema, [httpPart]) - 使用默认(或自定义)ValidationCompiler 编译指定的模式并返回验证函数。如果提供,则将可选的 httpPart 转发到 ValidationCompiler,默认为 null
  • .validateInput(data, schema | httpPart, [httpPart]) - 通过使用指定的模式验证指定的输入并返回序列化的负载。如果提供了可选的 httpPart,则该函数将使用为此 HTTP 状态代码提供的序列化函数。默认为 null

标头

request.headers 是一个 getter,它返回一个包含传入请求标头的对象。您可以像这样设置自定义标头

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

此操作将在请求标头中添加新值,可以通过调用 request.headers.bar 读取这些值。此外,您仍然可以通过 request.raw.headers 属性访问标准请求的标头。

注意:出于性能原因,在“未找到”路由上,您可能会看到我们在标头中添加了一个额外的属性 Symbol('fastify.RequestAcceptVersion')

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

此函数具有 errors 属性。上次验证期间遇到的错误被分配给 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])

.compileValidationSchema(schema,[httpPart])

此函数将编译验证模式并返回一个可用于验证数据的函数。返回的函数(也称为验证函数)是通过使用提供的 SchemaController#ValidationCompiler 编译的。使用 WeakMap 对其进行缓存,从而减少编译调用次数。

如果提供,则可选参数 httpPart 将直接转发到 ValidationCompiler,因此如果为路由提供了自定义 ValidationCompiler,则可以使用它来编译验证函数。

此函数具有 errors 属性。上次验证期间遇到的错误被分配给 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

请注意,在使用此函数时应谨慎,因为它将根据提供的模式缓存已编译的验证函数。如果提供的模式发生变异或更改,则验证函数将无法检测到模式已更改,例如,它将重用先前编译的验证函数,因为缓存基于先前提供的模式(对象)的引用。

如果需要更改模式的属性,始终选择创建一个全新的模式(对象),否则实现将无法从缓存机制中获益。

以以下模式为例

const schema1 = {
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}

不要

const validate = request.compileValidationSchema(schema1)

// Later on...
schema1.properties.foo.type. = 'integer'
const newValidate = request.compileValidationSchema(schema1)

console.log(newValidate === validate) // true

而是

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 参数将优先。

如果给定 schema 没有验证函数,则将编译一个新的验证函数,并在提供时转发 httpPart

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])