Skip to main content

工厂

工厂

¥Factory

Fastify 模块导出一个工厂函数,用于创建新的 Fastify server 实例。该工厂函数接受一个选项对象,用于自定义生成的实例。本文档描述了该选项对象中可用的属性。

¥The Fastify module exports a factory function that is used to create new Fastify server instances. This factory function accepts an options object which is used to customize the resulting instance. This document describes the properties available in that options object.

http

  • 默认:null

    ¥Default: null

用于配置服务器监听套接字的对象。选项与 Node.js 核心 createServer 方法 相同。

¥An object used to configure the server's listening socket. The options are the same as the Node.js core createServer method.

如果设置了选项 http2https,则忽略此选项。

¥This option is ignored if options http2 or https are set.

http2

  • 默认:false

    ¥Default: false

如果 true Node.js 核心的 HTTP/2 模块用于绑定套接字。

¥If true Node.js core's HTTP/2 module is used for binding the socket.

https

  • 默认:null

    ¥Default: null

用于配置服务器的 TLS 监听套接字的对象。选项与 Node.js 核心 createServer 方法 相同。当此属性为 null 时,套接字将不会配置为 TLS。

¥An object used to configure the server's listening socket for TLS. The options are the same as the Node.js core createServer method. When this property is null, the socket will not be configured for TLS.

当设置 http2 选项时,此选项也适用。

¥This option also applies when the http2 option is set.

connectionTimeout

  • 默认:0(无超时)

    ¥Default: 0 (no timeout)

定义服务器超时(以毫秒为单位)。查看 server.timeout property 的文档以了解此选项的效果。

¥Defines the server timeout in milliseconds. See documentation for server.timeout property to understand the effect of this option.

当指定 serverFactory 选项时,此选项将被忽略。

¥When serverFactory option is specified this option is ignored.

keepAliveTimeout

  • 默认:72000(72 秒)

    ¥Default: 72000 (72 seconds)

定义服务器保持活动超时(以毫秒为单位)。查看 server.keepAliveTimeout property 的文档以了解此选项的效果。此选项仅在使用 HTTP/1 时适用。

¥Defines the server keep-alive timeout in milliseconds. See documentation for server.keepAliveTimeout property to understand the effect of this option. This option only applies when HTTP/1 is in use.

当指定 serverFactory 选项时,此选项将被忽略。

¥When serverFactory option is specified this option is ignored.

forceCloseConnections

  • 默认:如果 HTTP 服务器允许,则为 "idle",否则为 false

    ¥Default: "idle" if the HTTP server allows it, false otherwise

设置为 true 时,在 close 上,服务器将迭代当前持久连接和 摧毁他们的插座

¥When set to true, upon close the server will iterate the current persistent connections and destroy their sockets.

警告 不会检查连接以确定请求是否已完成。

¥Connections are not inspected to determine if requests have been completed.

如果支持,Fastify 将优先使用 HTTP 服务器的 closeAllConnections 方法,否则,它将使用内部连接跟踪。

¥Fastify will prefer the HTTP server's closeAllConnections method if supported, otherwise, it will use internal connection tracking.

设置为 "idle" 时,在 close 上,服务器将迭代当前未发送请求或等待响应的持久连接并销毁其套接字。仅当 HTTP 服务器支持 closeIdleConnections 方法时才支持该值,否则尝试设置它将引发异常。

¥When set to "idle", upon close the server will iterate the current persistent connections which are not sending a request or waiting for a response and destroy their sockets. The value is only supported if the HTTP server supports the closeIdleConnections method, otherwise attempting to set it will throw an exception.

maxRequestsPerSocket

  • 默认:0(无限制)

    ¥Default: 0 (no limit)

定义在关闭保持活动连接之前套接字可以处理的最大请求数。有关此选项的效果 ...此选项仅在使用 HTTP/1.1 时适用。此外,当指定 serverFactory 选项时,此选项将被忽略。

¥Defines the maximum number of requests a socket can handle before closing keep alive connection. See server.maxRequestsPerSocket property to understand the effect of this option. This option only applies when HTTP/1.1 is in use. Also, when serverFactory option is specified, this option is ignored.

注意 在撰写本文时,只有 node >= v16.10.0 支持此选项。

¥At the time of writing, only node >= v16.10.0 supports this option.

requestTimeout

  • 默认:0(无限制)

    ¥Default: 0 (no limit)

定义从客户端接收整个请求的最大毫秒数。有关此选项的效果 ...

¥Defines the maximum number of milliseconds for receiving the entire request from the client. See server.requestTimeout property to understand the effect of this option.

当指定 serverFactory 选项时,此选项将被忽略。它必须设置为非零值(例如 120 秒),以防止在服务器部署在前面没有反向代理的情况下潜在的拒绝服务攻击。

¥When serverFactory option is specified, this option is ignored. It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.

注意 在撰写本文时,只有 node >= v14.11.0 支持此选项

¥At the time of writing, only node >= v14.11.0 supports this option

ignoreTrailingSlash

  • 默认:false

    ¥Default: false

Fastify 使用 find-my-way 来处理路由。默认情况下,Fastify 将考虑尾部斜杠。像 /foo/foo/ 这样的路径被视为不同的路径。如果你想更改这一点,请将此标志设置为 true。这样,/foo/foo/ 都将指向相同的路由。此选项适用于生成的服务器实例的所有路由注册。

¥Fastify uses find-my-way to handle routing. By default, Fastify will take into account the trailing slashes. Paths like /foo and /foo/ are treated as different paths. If you want to change this, set this flag to true. That way, both /foo and /foo/ will point to the same route. This option applies to all route registrations for the resulting server instance.

const fastify = require('fastify')({
ignoreTrailingSlash: true
})

// registers both "/foo" and "/foo/"
fastify.get('/foo/', function (req, reply) {
reply.send('foo')
})

// registers both "/bar" and "/bar/"
fastify.get('/bar', function (req, reply) {
reply.send('bar')
})

ignoreDuplicateSlashes

  • 默认:false

    ¥Default: false

Fastify 使用 find-my-way 来处理路由。你可以使用 ignoreDuplicateSlashes 选项从路径中删除重复的斜杠。它会删除路由路径和请求 URL 中的重复斜杠。此选项适用于生成的服务器实例的所有路由注册。

¥Fastify uses find-my-way to handle routing. You can use ignoreDuplicateSlashes option to remove duplicate slashes from the path. It removes duplicate slashes in the route path and the request URL. This option applies to all route registrations for the resulting server instance.

ignoreTrailingSlashignoreDuplicateSlashes 都设置为 true 时,Fastify 将删除重复的斜杠,然后是尾随斜杠,这意味着 //a//b//c// 将转换为 /a/b/c

¥When ignoreTrailingSlash and ignoreDuplicateSlashes are both set to true Fastify will remove duplicate slashes, and then trailing slashes, meaning //a//b//c// will be converted to /a/b/c.

const fastify = require('fastify')({
ignoreDuplicateSlashes: true
})

// registers "/foo/bar/"
fastify.get('///foo//bar//', function (req, reply) {
reply.send('foo')
})

maxParamLength

  • 默认:100

    ¥Default: 100

你可以使用 maxParamLength 选项为参数(标准、正则表达式和多)路由中的参数设置自定义长度;默认值为 100 个字符。如果达到最大长度限制,则将调用未找到的路由。

¥You can set a custom length for parameters in parametric (standard, regex, and multi) routes by using maxParamLength option; the default value is 100 characters. If the maximum length limit is reached, the not found route will be invoked.

如果你有基于正则表达式的路由,这非常有用,可以保护你免受 ReDoS 攻击 的攻击。

¥This can be useful especially if you have a regex-based route, protecting you against ReDoS attacks.

bodyLimit

  • 默认:1048576(1MiB)

    ¥Default: 1048576 (1MiB)

定义服务器允许接受的最大有效负载(以字节为单位)。如果正文的大小超出此限制,默认正文读取器将发送 FST_ERR_CTP_BODY_TOO_LARGE 回复。如果提供了 preParsing,则此限制将应用于钩子返回的流的大小(即 "decoded" 主体的大小)。

¥Defines the maximum payload, in bytes, the server is allowed to accept. The default body reader sends FST_ERR_CTP_BODY_TOO_LARGE reply, if the size of the body exceeds this limit. If preParsing hook is provided, this limit is applied to the size of the stream the hook returns (i.e. the size of "decoded" body).

onProtoPoisoning

  • 默认:'error'

    ¥Default: 'error'

定义使用 __proto__ 解析 JSON 对象时框架必须采取的操作。此功能由 secure-json-parse 提供。请参阅 原型中毒 了解原型中毒攻击的更多详细信息。

¥Defines what action the framework must take when parsing a JSON object with __proto__. This functionality is provided by secure-json-parse. See Prototype Poisoning for more details about prototype poisoning attacks.

可能的值是 'error''remove''ignore'

¥Possible values are 'error', 'remove', or 'ignore'.

onConstructorPoisoning

  • 默认:'error'

    ¥Default: 'error'

定义使用 constructor 解析 JSON 对象时框架必须采取的操作。此功能由 secure-json-parse 提供。请参阅 原型中毒 了解原型中毒攻击的更多详细信息。

¥Defines what action the framework must take when parsing a JSON object with constructor. This functionality is provided by secure-json-parse. See Prototype Poisoning for more details about prototype poisoning attacks.

可能的值是 'error''remove''ignore'

¥Possible values are 'error', 'remove', or 'ignore'.

logger

Fastify 通过 Pino 日志器包含内置日志记录。该属性用于配置内部日志器实例。

¥Fastify includes built-in logging via the Pino logger. This property is used to configure the internal logger instance.

该属性可能具有的值有:

¥The possible values this property may have are:

  • 默认:false。日志器被禁用。所有日志记录方法都将指向一个空的日志器 abstract-logging 实例。

    ¥Default: false. The logger is disabled. All logging methods will point to a null logger abstract-logging instance.

  • object:标准的 Pino 选项对象。这将直接传递给 Pino 构造函数。如果对象上不存在以下属性,则会相应地添加它们:

    ¥object: a standard Pino options object. This will be passed directly to the Pino constructor. If the following properties are not present on the object, they will be added accordingly:

    • level:最低日志记录级别。如果未设置,它将被设置为 'info'

      ¥level: the minimum logging level. If not set, it will be set to 'info'.

    • serializers:序列化函数的哈希值。默认情况下,为 req(传入请求对象)、res(传出响应对象)和 err(标准 Error 对象)添加序列化器。当日志方法接收到具有任何这些属性的对象时,相应的序列化程序将用于该属性。例如:

      ¥serializers: a hash of serialization functions. By default, serializers are added for req (incoming request objects), res (outgoing response objects), and err (standard Error objects). When a log method receives an object with any of these properties then the respective serializer will be used for that property. For example:

      fastify.get('/foo', function (req, res) {
      req.log.info({req}) // log the serialized request object
      res.send('foo')
      })

      任何用户提供的序列化程序都将覆盖相应属性的默认序列化程序。

      ¥Any user-supplied serializer will override the default serializer of the corresponding property.

loggerInstance

  • 默认:null

    ¥Default: null

自定义日志器实例。日志器必须是 Pino 实例或符合 Pino 接口,具有以下方法:info, error, debug, fatal, warn, trace, child.例如:

¥A custom logger instance. The logger must be a Pino instance or conform to the Pino interface by having the following methods: info, error, debug, fatal, warn, trace, child. For example:

const pino = require('pino')();

const customLogger = {
info: function (o, ...n) {},
warn: function (o, ...n) {},
error: function (o, ...n) {},
fatal: function (o, ...n) {},
trace: function (o, ...n) {},
debug: function (o, ...n) {},
child: function() {
const child = Object.create(this);
child.pino = pino.child(...arguments);
return child;
},
};

const fastify = require('fastify')({logger: customLogger});

disableRequestLogging

  • 默认:false

    ¥Default: false

当启用日志记录时,Fastify 将在收到请求并发送该请求的响应时发出 info 级别的日志消息。通过将此选项设置为 true,这些日志消息将被禁用。通过附加自定义 onRequestonResponse 钩子,可以更灵活地记录请求的开始和结束。

¥When logging is enabled, Fastify will issue an info level log message when a request is received and when the response for that request has been sent. By setting this option to true, these log messages will be disabled. This allows for more flexible request start and end logging by attaching custom onRequest and onResponse hooks.

将被禁用的其他日志条目是:

¥The other log entries that will be disabled are:

  • 默认 onResponse 钩子在回复回调错误时写入的错误日志

    ¥an error log written by the default onResponse hook on reply callback errors

  • defaultErrorHandler 在错误管理上写入的错误和信息日志

    ¥the error and info logs written by the defaultErrorHandler on error management

  • 请求不存在的路由时由 fourOhFour 处理程序写入的信息日志

    ¥the info log written by the fourOhFour handler when a non existent route is requested

Fastify 发出的其他日志消息将保持启用状态,例如弃用警告以及在服务器关闭时收到请求时发出的消息。

¥Other log messages emitted by Fastify will stay enabled, like deprecation warnings and messages emitted when requests are received while the server is closing.

// Examples of hooks to replicate the disabled functionality.
fastify.addHook('onRequest', (req, reply, done) => {
req.log.info({ url: req.raw.url, id: req.id }, 'received request')
done()
})

fastify.addHook('onResponse', (req, reply, done) => {
req.log.info({ url: req.raw.originalUrl, statusCode: reply.raw.statusCode }, 'request completed')
done()
})

serverFactory

你可以使用 serverFactory 选项将自定义 HTTP 服务器传递给 Fastify。

¥You can pass a custom HTTP server to Fastify by using the serverFactory option.

serverFactory 是一个函数,它接受一个 handler 参数,该参数以 requestresponse 对象作为参数,以及一个选项对象,该对象与你传递给 Fastify 的对象相同。

¥serverFactory is a function that takes a handler parameter, which takes the request and response objects as parameters, and an options object, which is the same you have passed to Fastify.

const serverFactory = (handler, opts) => {
const server = http.createServer((req, res) => {
handler(req, res)
})

return server
}

const fastify = Fastify({ serverFactory })

fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})

fastify.listen({ port: 3000 })

Fastify 内部使用 Node 核心 HTTP 服务器的 API,因此如果你使用自定义服务器,则必须确保公开相同的 API。如果没有,你可以在 return 语句之前增强 serverFactory 函数内的服务器实例。

¥Internally Fastify uses the API of Node core HTTP server, so if you are using a custom server you must be sure to have the same API exposed. If not, you can enhance the server instance inside the serverFactory function before the return statement.

caseSensitive

  • 默认:true

    ¥Default: true

true 路由注册为区分大小写时。也就是说,/foo 不等于 /Foo。当 false 路由不区分大小写时。

¥When true routes are registered as case-sensitive. That is, /foo is not equal to /Foo. When false then routes are case-insensitive.

请注意,将此选项设置为 falseRFC3986 相悖。

¥Please note that setting this option to false goes against RFC3986.

通过将 caseSensitive 设置为 false,所有路径都将匹配为小写,但路由参数或通配符将保持其原始字母大小写。此选项不影响查询字符串,请参阅 querystringParser 以更改其处理方式。

¥By setting caseSensitive to false, all paths will be matched as lowercase, but the route parameters or wildcards will maintain their original letter casing. This option does not affect query strings, please refer to querystringParser to change their handling.

fastify.get('/user/:username', (request, reply) => {
// Given the URL: /USER/NodeJS
console.log(request.params.username) // -> 'NodeJS'
})

allowUnsafeRegex

  • 默认 false

    ¥Default false

默认情况下禁用,因此路由仅允许安全正则表达式。要使用不安全的表达式,请将 allowUnsafeRegex 设置为 true

¥Disabled by default, so routes only allow safe regular expressions. To use unsafe expressions, set allowUnsafeRegex to true.

fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => {
// Throws an error without allowUnsafeRegex = true
})

requestIdHeader

  • 默认:'request-id'

    ¥Default: 'request-id'

用于设置 request-id 的标头名称。参见 请求 ID 部分。将 requestIdHeader 设置为 true 会将 requestIdHeader 设置为 "request-id"。将 requestIdHeader 设置为非空字符串会将指定的字符串用作 requestIdHeader。默认情况下,requestIdHeader 设置为 false 并将立即使用 genReqId。将 requestIdHeader 设置为空字符串 ("") 会将 requestIdHeader 设置为 false

¥The header name used to set the request-id. See the request-id section. Setting requestIdHeader to true will set the requestIdHeader to "request-id". Setting requestIdHeader to a non-empty string will use the specified string as the requestIdHeader. By default requestIdHeader is set to false and will immediately use genReqId. Setting requestIdHeader to an empty String ("") will set the requestIdHeader to false.

  • 默认:false

    ¥Default: false

const fastify = require('fastify')({
requestIdHeader: 'x-custom-id', // -> use 'X-Custom-Id' header if available
//requestIdHeader: false, // -> always use genReqId
})

requestIdLogLabel

  • 默认:'reqId'

    ¥Default: 'reqId'

定义记录请求时用于请求标识符的标签。

¥Defines the label used for the request identifier when logging the request.

genReqId

  • 默认:value of 'request-id' header if provided or monotonically increasing integers

    ¥Default: value of 'request-id' header if provided or monotonically increasing integers

用于生成 request-id 的函数。它将接收原始传入请求作为参数。该函数预计不会出现错误。

¥Function for generating the request-id. It will receive the raw incoming request as a parameter. This function is expected to be error-free.

特别是在分布式系统中,你可能想要覆盖默认的 ID 生成行为,如下所示。要生成 UUID,你可能需要查看 hyperid

¥Especially in distributed systems, you may want to override the default ID generation behavior as shown below. For generating UUIDs you may want to check out hyperid.

注意 如果 requestIdHeader 中设置的标头可用(默认为 'request-id'),则不会调用 genReqId

¥genReqId will be not called if the header set in requestIdHeader is available (defaults to 'request-id').

let i = 0
const fastify = require('fastify')({
genReqId: function (req) { return i++ }
})

trustProxy

  • 默认:false

    ¥Default: false

  • true/false:信任所有代理(true)或不信任任何代理(false)。

    ¥true/false: Trust all proxies (true) or do not trust any proxies (false).

  • string:仅信任给定的 IP/CIDR(例如 '127.0.0.1')。可能是逗号分隔值的列表(例如 '127.0.0.1,192.168.1.1/24')。

    ¥string: Trust only given IP/CIDR (e.g. '127.0.0.1'). May be a list of comma separated values (e.g. '127.0.0.1,192.168.1.1/24').

  • Array<string>:仅信任给定的 IP/CIDR 列表(例如 ['127.0.0.1'])。

    ¥Array<string>: Trust only given IP/CIDR list (e.g. ['127.0.0.1']).

  • number:信任来自前端代理服务器的第 n 个跃点作为客户端。

    ¥number: Trust the nth hop from the front-facing proxy server as the client.

  • Function:以 address 作为第一个参数的自定义信任函数

    ¥Function: Custom trust function that takes address as first argument

    function myTrustFn(address, hop) {
    return address === '1.2.3.4' || hop === 1
    }

通过启用 trustProxy 选项,Fastify 将知道它位于代理后面,并且 X-Forwarded-* 标头字段可能是可信的,否则可能很容易被欺骗。

¥By enabling the trustProxy option, Fastify will know that it is sitting behind a proxy and that the X-Forwarded-* header fields may be trusted, which otherwise may be easily spoofed.

const fastify = Fastify({ trustProxy: true })

有关更多示例,请参阅 proxy-addr 包。

¥For more examples, refer to the proxy-addr package.

你可以在 request 对象上访问 ipipshostprotocol 值。

¥You may access the ip, ips, host and protocol values on the request object.

fastify.get('/', (request, reply) => {
console.log(request.ip)
console.log(request.ips)
console.log(request.host)
console.log(request.protocol)
})

注意 如果请求包含多个 x-forwarded-hostx-forwarded-proto 标头,则只有最后一个标头用于派生 request.hostnamerequest.protocol

¥If a request contains multiple x-forwarded-host or x-forwarded-proto headers, it is only the last one that is used to derive request.hostname and request.protocol.

pluginTimeout

  • 默认:10000

    ¥Default: 10000

插件可以加载的最长时间(以毫秒为单位)。如果没有,ready 将使用代码 'ERR_AVVIO_PLUGIN_TIMEOUT'Error 完成。当设置为 0 时,禁用此检查。这控制 avviotimeout 参数。

¥The maximum amount of time in milliseconds in which a plugin can load. If not, ready will complete with an Error with code 'ERR_AVVIO_PLUGIN_TIMEOUT'. When set to 0, disables this check. This controls avvio 's timeout parameter.

querystringParser

Fastify 使用的默认查询字符串解析器是 Node.js 的核心 querystring 模块。

¥The default query string parser that Fastify uses is the Node.js's core querystring module.

你可以使用此选项来使用自定义解析器,例如 qs

¥You can use this option to use a custom parser, such as qs.

如果你只希望键(而不是值)不区分大小写,我们建议使用自定义解析器仅将键转换为小写。

¥If you only want the keys (and not the values) to be case insensitive we recommend using a custom parser to convert only the keys to lowercase.

const qs = require('qs')
const fastify = require('fastify')({
querystringParser: str => qs.parse(str)
})

你还可以使用 Fastify 的默认解析器,但更改一些处理行为,如下面不区分大小写的键和值的示例:

¥You can also use Fastify's default parser but change some handling behavior, like the example below for case insensitive keys and values:

const querystring = require('node:querystring')
const fastify = require('fastify')({
querystringParser: str => querystring.parse(str.toLowerCase())
})

exposeHeadRoutes

  • 默认:true

    ¥Default: true

为每个定义的 GET 路由自动创建一个同级 HEAD 路由。如果你想要自定义 HEAD 处理程序而不禁用此选项,请确保在 GET 路由之前定义它。

¥Automatically creates a sibling HEAD route for each GET route defined. If you want a custom HEAD handler without disabling this option, make sure to define it before the GET route.

constraints

Fastify 的内置路由约束由 find-my-way 提供,允许通过 versionhost 约束路由。你可以通过为 constraints 对象提供针对 find-my-way 的策略来添加新的约束策略或覆盖内置策略。你可以在 find-my-way 文档中找到有关约束策略的更多信息。

¥Fastify's built-in route constraints are provided by find-my-way, which allows constraining routes by version or host. You can add new constraint strategies, or override the built-in strategies, by providing a constraints object with strategies for find-my-way. You can find more information on constraint strategies in the find-my-way documentation.

const customVersionStrategy = {
storage: function () {
const versions = {}
return {
get: (version) => { return versions[version] || null },
set: (version, store) => { versions[version] = store }
}
},
deriveVersion: (req, ctx) => {
return req.headers['accept']
}
}

const fastify = require('fastify')({
constraints: {
version: customVersionStrategy
}
})

return503OnClosing

  • 默认:true

    ¥Default: true

调用 close 服务器方法后返回 503。如果是 false,服务器将照常路由传入请求。

¥Returns 503 after calling close server method. If false, the server routes the incoming request as usual.

ajv

配置 Fastify 使用的 Ajv v8 实例,无需提供自定义实例。默认配置在 #schema-validator 部分中说明。

¥Configure the Ajv v8 instance used by Fastify without providing a custom one. The default configuration is explained in the #schema-validator section.

const fastify = require('fastify')({
ajv: {
customOptions: {
removeAdditional: 'all' // Refer to [ajv options](https://ajv.nodejs.cn/options.html#removeadditional)
},
plugins: [
require('ajv-merge-patch'),
[require('ajv-keywords'), 'instanceof']
// Usage: [plugin, pluginOptions] - Plugin with options
// Usage: plugin - Plugin without options
]
}
})

serializerOpts

自定义序列化响应有效负载的默认 fast-json-stringify 实例的选项:

¥Customize the options of the default fast-json-stringify instance that serializes the response's payload:

const fastify = require('fastify')({
serializerOpts: {
rounding: 'ceil'
}
})

http2SessionTimeout

  • 默认:72000

    ¥Default: 72000

为每个传入的 HTTP/2 会话设置一个默认 timeout(以毫秒为单位)。会话将在超时时关闭。

¥Set a default timeout to every incoming HTTP/2 session in milliseconds. The session will be closed on the timeout.

使用 HTTP/2 时,需要此选项来提供优雅的 "close" 体验。选择较低的默认值是为了减轻拒绝服务攻击。当服务器位于负载均衡器后面或可以自动扩展时,可以增加该值以适应用例。Node 核心默认将其设置为 0

¥This option is needed to offer a graceful "close" experience when using HTTP/2. The low default has been chosen to mitigate denial of service attacks. When the server is behind a load balancer or can scale automatically this value can be increased to fit the use case. Node core defaults this to 0.

frameworkErrors

  • 默认:null

    ¥Default: null

Fastify 为最常见的用例提供默认错误处理程序。使用此选项可以使用自定义代码覆盖一个或多个处理程序。

¥Fastify provides default error handlers for the most common use cases. It is possible to override one or more of those handlers with custom code using this option.

注意 目前只实现了 FST_ERR_BAD_URLFST_ERR_ASYNC_CONSTRAINT

¥Only FST_ERR_BAD_URL and FST_ERR_ASYNC_CONSTRAINT are implemented at present.

const fastify = require('fastify')({
frameworkErrors: function (error, req, res) {
if (error instanceof FST_ERR_BAD_URL) {
res.code(400)
return res.send("Provided url is not valid")
} else if(error instanceof FST_ERR_ASYNC_CONSTRAINT) {
res.code(400)
return res.send("Provided header is not valid")
} else {
res.send(err)
}
}
})

clientErrorHandler

设置一个 clientErrorHandler,用于监听客户端连接发出的 error 事件并以 400 响应。

¥Set a clientErrorHandler that listens to error events emitted by client connections and responds with a 400.

可以使用此选项覆盖默认的 clientErrorHandler

¥It is possible to override the default clientErrorHandler using this option.

  • 默认:

    ¥Default:

function defaultClientErrorHandler (err, socket) {
if (err.code === 'ECONNRESET') {
return
}

const body = JSON.stringify({
error: http.STATUS_CODES['400'],
message: 'Client Error',
statusCode: 400
})
this.log.trace({ err }, 'client error')

if (socket.writable) {
socket.end([
'HTTP/1.1 400 Bad Request',
`Content-Length: ${body.length}`,
`Content-Type: application/json\r\n\r\n${body}`
].join('\r\n'))
}
}

注意 clientErrorHandler 使用原始套接字操作。处理程序应返回格式正确的 HTTP 响应,其中包括状态行、HTTP 标头和消息正文。在尝试写入套接字之前,处理程序应检查套接字是否仍然可写,因为它可能已经被销毁。

¥clientErrorHandler operates with raw sockets. The handler is expected to return a properly formed HTTP response that includes a status line, HTTP headers and a message body. Before attempting to write the socket, the handler should check if the socket is still writable as it may have already been destroyed.

const fastify = require('fastify')({
clientErrorHandler: function (err, socket) {
const body = JSON.stringify({
error: {
message: 'Client error',
code: '400'
}
})

// `this` is bound to fastify instance
this.log.trace({ err }, 'client error')

// the handler is responsible for generating a valid HTTP response
socket.end([
'HTTP/1.1 400 Bad Request',
`Content-Length: ${body.length}`,
`Content-Type: application/json\r\n\r\n${body}`
].join('\r\n'))
}
})

rewriteUrl

设置同步回调函数,该函数必须返回允许重写 URL 的字符串。当你位于更改 URL 的代理后面时,这非常有用。重写 URL 将修改 req 对象的 url 属性。

¥Set a sync callback function that must return a string that allows rewriting URLs. This is useful when you are behind a proxy that changes the URL. Rewriting a URL will modify the url property of the req object.

请注意,rewriteUrl 在路由之前被调用,它没有被封装,它是一个实例范围的配置。

¥Note that rewriteUrl is called before routing, it is not encapsulated and it is an instance-wide configuration.

// @param {object} req The raw Node.js HTTP request, not the `FastifyRequest` object.
// @this Fastify The root Fastify instance (not an encapsulated instance).
// @returns {string} The path that the request should be mapped to.
function rewriteUrl (req) {
if (req.url === '/hi') {
this.log.debug({ originalUrl: req.url, url: '/hello' }, 'rewrite url');
return '/hello'
} else {
return req.url;
}
}

useSemicolonDelimiter

  • 默认 false

    ¥Default false

Fastify 使用 find-my-way,它支持使用 ; 字符(代码 59)分隔路径和查询字符串,例如 /dev;foo=bar。此决定源自 [delvedor/find-my-way#76] (https://github.com/delvedor/find-my-way/issues/76)。因此,此选项将支持向后兼容,以满足在 ; 上拆分的需求。要启用对 ; 上拆分的支持,请将 useSemicolonDelimiter 设置为 true

¥Fastify uses find-my-way which supports, separating the path and query string with a ; character (code 59), e.g. /dev;foo=bar. This decision originated from [delvedor/find-my-way#76] (https://github.com/delvedor/find-my-way/issues/76). Thus, this option will support backwards compatiblilty for the need to split on ;. To enable support for splitting on ; set useSemicolonDelimiter to true.

const fastify = require('fastify')({
useSemicolonDelimiter: true
})

fastify.get('/dev', async (request, reply) => {
// An example request such as `/dev;foo=bar`
// Will produce the following query params result `{ foo = 'bar' }`
return request.query
})

实例

¥Instance

服务器方法

¥Server Methods

server

fastify.serverFastify factory function 返回的 Node 核心 server 对象。

¥fastify.server: The Node core server object as returned by the Fastify factory function.

警告 如果使用不当,某些 Fastify 功能可能会中断。建议仅将其用于附加监听器。

¥If utilized improperly, certain Fastify features could be disrupted. It is recommended to only use it for attaching listeners.

after

当当前插件以及其中注册的所有插件完成加载时调用。它总是在方法 fastify.ready 之前执行。

¥Invoked when the current plugin and all the plugins that have been registered within it have finished loading. It is always executed before the method fastify.ready.

fastify
.register((instance, opts, done) => {
console.log('Current plugin')
done()
})
.after(err => {
console.log('After current plugin')
})
.register((instance, opts, done) => {
console.log('Next plugin')
done()
})
.ready(err => {
console.log('Everything has been loaded')
})

如果在没有函数的情况下调用 after(),它将返回 Promise

¥In case after() is called without a function, it returns a Promise:

fastify.register(async (instance, opts) => {
console.log('Current plugin')
})

await fastify.after()
console.log('After current plugin')

fastify.register(async (instance, opts) => {
console.log('Next plugin')
})

await fastify.ready()

console.log('Everything has been loaded')

ready

加载所有插件后调用的函数。如果出现问题,它需要一个错误参数。

¥Function called when all the plugins have been loaded. It takes an error parameter if something went wrong.

fastify.ready(err => {
if (err) throw err
})

如果在没有任何参数的情况下调用它,它将返回 Promise

¥If it is called without any arguments, it will return a Promise:

fastify.ready().then(() => {
console.log('successfully booted!')
}, (err) => {
console.log('an error happened', err)
})

listen

启动服务器并在内部等待 .ready() 事件。签名为 .listen([options][, callback])options 对象和 callback 参数都扩展了 Node.js 核心 选项对象。因此,所有核心选项都可通过以下附加 Fastify 特定选项使用:

¥Starts the server and internally waits for the .ready() event. The signature is .listen([options][, callback]). Both the options object and the callback parameters extend the Node.js core options object. Thus, all core options are available with the following additional Fastify specific options:

listenTextResolver

为服务器成功启动后要记录的文本设置可选解析程序。可以使用此选项覆盖默认的 Server listening at [address] 日志条目。

¥Set an optional resolver for the text to log after server has been successfully started. It is possible to override the default Server listening at [address] log entry using this option.

server.listen({
port: 9080,
listenTextResolver: (address) => { return `Prometheus metrics server is listening at ${address}` }
})

默认情况下,当未提供特定主机时,服务器将监听由 localhost 解析的地址。如果需要监听任何可用接口,则为地址指定 0.0.0.0 将监听所有 IPv4 地址。下表详细说明了针对 localhosthost 的可能值,以及这些值对 host 的结果是什么。

¥By default, the server will listen on the address(es) resolved by localhost when no specific host is provided. If listening on any available interface is desired, then specifying 0.0.0.0 for the address will listen on all IPv4 addresses. The following table details the possible values for host when targeting localhost, and what the result of those values for host will be.

主机IPv4IPv6
::*
:: + ipv6Only🚫
0.0.0.0🚫
localhost
127.0.0.1🚫
::1🚫
* 使用 `::` 作为地址将监听所有 IPv6 地址,并且根据操作系统的不同,也可能监听 [所有 IPv4 地址](https://nodejs.cn/api/net.html#serverlistenport-host-backlog-callback)。

¥* Using :: for the address will listen on all IPv6 addresses and, depending on OS, may also listen on all IPv4 addresses.

决定监听所有接口时要小心;它带有固有的 安全风险

¥Be careful when deciding to listen on all interfaces; it comes with inherent security risks.

默认是监听 port: 0(选择第一个可用的开放端口)和 host: 'localhost'

¥The default is to listen on port: 0 (which picks the first available open port) and host: 'localhost':

fastify.listen((err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})

还支持指定地址:

¥Specifying an address is also supported:

fastify.listen({ port: 3000, host: '127.0.0.1' }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})

如果没有提供回调,则返回 Promise:

¥If no callback is provided a Promise is returned:

fastify.listen({ port: 3000 })
.then((address) => console.log(`server listening on ${address}`))
.catch(err => {
console.log('Error starting server:', err)
process.exit(1)
})

当部署到 Docker 和其他容器时,建议监听 0.0.0.0,因为它们默认不将映射端口暴露给 localhost

¥When deploying to a Docker, and potentially other, containers, it is advisable to listen on 0.0.0.0 because they do not default to exposing mapped ports to localhost:

fastify.listen({ port: 3000, host: '0.0.0.0' }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})

如果省略 port(或将其设置为零),则会自动选择一个随机可用端口(可通过 fastify.server.address().port 获得)。

¥If the port is omitted (or is set to zero), a random available port is automatically chosen (available via fastify.server.address().port).

监听的默认选项是:

¥The default options of listen are:

fastify.listen({
port: 0,
host: 'localhost',
exclusive: false,
readableAll: false,
writableAll: false,
ipv6Only: false
}, (err) => {})

addresses

此方法返回服务器正在监听的地址数组。如果在调用 listen() 之前或在 close() 函数之后调用它,它将返回一个空数组。

¥This method returns an array of addresses that the server is listening on. If you call it before listen() is called or after the close() function, it will return an empty array.

await fastify.listen({ port: 8080 })
const addresses = fastify.addresses()
// [
// { port: 8080, family: 'IPv6', address: '::1' },
// { port: 8080, family: 'IPv4', address: '127.0.0.1' }
// ]

请注意,数组也包含 fastify.server.address()

¥Note that the array contains the fastify.server.address() too.

routing

访问内部路由的 lookup 方法并将请求与适当的处理程序匹配的方法:

¥Method to access the lookup method of the internal router and match the request to the appropriate handler:

fastify.routing(req, res)

route

向服务器添加路由的方法,它还具有简写函数,请检查 此处

¥Method to add routes to the server, it also has shorthand functions, check here.

hasRoute

检查路由是否已注册到内部路由的方法。它期望一个对象作为有效负载。urlmethod 是必填字段。也可以指定 constraints。如果路由已注册,则该方法返回 true,否则返回 false

¥Method to check if a route is already registered to the internal router. It expects an object as the payload. url and method are mandatory fields. It is possible to also specify constraints. The method returns true if the route is registered or false if not.

const routeExists = fastify.hasRoute({
url: '/',
method: 'GET',
constraints: { version: '1.0.0' } // optional
})

if (routeExists === false) {
// add route
}

findRoute

检索已注册到内部路由的路由的方法。它期望一个对象作为有效负载。urlmethod 是必填字段。也可以指定 constraints。如果找不到路由,则该方法返回路由对象或 null

¥Method to retrieve a route already registered to the internal router. It expects an object as the payload. url and method are mandatory fields. It is possible to also specify constraints. The method returns a route object or null if the route cannot be found.

const route = fastify.findRoute({
url: '/artists/:artistId',
method: 'GET',
constraints: { version: '1.0.0' } // optional
})

if (route !== null) {
// perform some route checks
console.log(route.params) // `{artistId: ':artistId'}`
}

close

fastify.close(callback):调用此函数关闭服务器实例并运行 'onClose' 钩子。

¥fastify.close(callback): call this function to close the server instance and run the 'onClose' hook.

调用 close 还会导致服务器对每个新传入请求都响应 503 错误并销毁该请求。请参阅 return503OnClosing 标志 了解更改此行为的方法。

¥Calling close will also cause the server to respond to every new incoming request with a 503 error and destroy that request. See return503OnClosing flags for changing this behavior.

如果不带任何参数调用它,它将返回一个 Promise:

¥If it is called without any arguments, it will return a Promise:

fastify.close().then(() => {
console.log('successfully closed!')
}, (err) => {
console.log('an error happened', err)
})

decorate*

如果你需要装饰 fastify 实例、回复或请求,则该函数很有用,请检查 此处

¥Function useful if you need to decorate the fastify instance, Reply or Request, check here.

register

Fastify 允许用户通过插件扩展其功能。插件可以是一组路由、服务器装饰器或其他任何东西,请检查 此处

¥Fastify allows the user to extend its functionality with plugins. A plugin can be a set of routes, a server decorator, or whatever, check here.

addHook

用于在 Fastify 的生命周期中添加特定钩子的函数,请检查 此处

¥Function to add a specific hook in the lifecycle of Fastify, check here.

prefix

将作为路由前缀的完整路径。

¥The full path that will be prefixed to a route.

示例:

¥Example:

fastify.register(function (instance, opts, done) {
instance.get('/foo', function (request, reply) {
// Will log "prefix: /v1"
request.log.info('prefix: %s', instance.prefix)
reply.send({ prefix: instance.prefix })
})

instance.register(function (instance, opts, done) {
instance.get('/bar', function (request, reply) {
// Will log "prefix: /v1/v2"
request.log.info('prefix: %s', instance.prefix)
reply.send({ prefix: instance.prefix })
})

done()
}, { prefix: '/v2' })

done()
}, { prefix: '/v1' })

pluginName

当前插件的名称。根插件称为 'fastify'。定义名称有不同的方法(按顺序)。

¥Name of the current plugin. The root plugin is called 'fastify'. There are different ways to define a name (in order).

  1. 如果你使用 fastify-plugin,则使用元数据 name

    ¥If you use fastify-plugin the metadata name is used.

  2. 如果导出的插件具有 Symbol.for('fastify.display-name') 属性,则使用该属性的值。示例:pluginFn[Symbol.for('fastify.display-name')] = "Custom Name"

    ¥If the exported plugin has the Symbol.for('fastify.display-name') property, then the value of that property is used. Example: pluginFn[Symbol.for('fastify.display-name')] = "Custom Name"

  3. 如果你 module.exports 插件,则使用文件名。

    ¥If you module.exports a plugin the filename is used.

  4. 如果你使用常规 函数声明,则使用函数名称。

    ¥If you use a regular function declaration the function name is used.

倒退:插件的前两行将代表插件名称。换行符被 -- 替换。当你处理许多插件时,这将有助于确定根本原因。

¥Fallback: The first two lines of your plugin will represent the plugin name. Newlines are replaced by --. This will help to identify the root cause when you deal with many plugins.

警告 如果你必须处理嵌套插件,则名称与 fastify-plugin 的用法不同,因为没有创建新的范围,因此我们没有地方附加上下文数据。在这种情况下,插件名称将以 fastify -> plugin-A -> plugin-B 的格式表示所有相关插件的启动顺序。

¥If you have to deal with nested plugins, the name differs with the usage of the fastify-plugin because no new scope is created and therefore we have no place to attach contextual data. In that case, the plugin name will represent the boot order of all involved plugins in the format of fastify -> plugin-A -> plugin-B.

hasPlugin

检查特定插件是否已注册的方法。依赖于插件元数据名称。如果插件已注册,则返回 true。否则,返回 false

¥Method to check if a specific plugin has been registered. Relies on the plugin metadata name. Returns true if the plugin is registered. Otherwise, returns false.

const fastify = require('fastify')()
fastify.register(require('@fastify/cookie'), {
secret: 'my-secret',
parseOptions: {}
})

fastify.ready(() => {
fastify.hasPlugin('@fastify/cookie') // true
})

listeningOrigin

服务器正在监听的当前源。例如,基于 TCP 套接字的服务器返回基地址,如 http://127.0.0.1:3000,而 Unix 套接字服务器将返回套接字路径,例如 fastify.temp.sock

¥The current origin the server is listening to. For example, a TCP socket based server returns a base address like http://127.0.0.1:3000, and a Unix socket server will return the socket path, e.g. fastify.temp.sock.

log

日志器实例,检查 此处

¥The logger instance, check here.

version

实例的 Fastify 版本。用于插件支持。请参阅 插件 了解插件如何使用版本的信息。

¥Fastify version of the instance. Used for plugin support. See Plugins for information on how the version is used by plugins.

inject

伪 HTTP 注入(用于测试目的)此处

¥Fake HTTP injection (for testing purposes) here.

addHttpMethod

Fastify 默认支持 GETHEADTRACEDELETEOPTIONSPATCHPUTPOST HTTP 方法。addHttpMethod 方法允许向服务器添加任何非标准 HTTP 方法,即 由 Node.js 支持

¥Fastify supports the GET, HEAD, TRACE, DELETE, OPTIONS, PATCH, PUT and POST HTTP methods by default. The addHttpMethod method allows to add any non standard HTTP methods to the server that are supported by Node.js.

// Add a new HTTP method called 'MKCOL' that supports a request body
fastify.addHttpMethod('MKCOL', { hasBody: true, })

// Add a new HTTP method called 'COPY' that does not support a request body
fastify.addHttpMethod('COPY')

调用 addHttpMethod 后,可以使用路由简写方法为新的 HTTP 方法定义路由:

¥After calling addHttpMethod, it is possible to use the route shorthand methods to define routes for the new HTTP method:

fastify.addHttpMethod('MKCOL', { hasBody: true })
fastify.mkcol('/', (req, reply) => {
// Handle the 'MKCOL' request
})

addSchema

fastify.addSchema(schemaObj),向 Fastify 实例添加 JSON 模式。这允许你仅使用标准 $ref 关键字在应用的任何地方重复使用它。

¥fastify.addSchema(schemaObj), adds a JSON schema to the Fastify instance. This allows you to reuse it everywhere in your application just by using the standard $ref keyword.

要了解更多信息,请阅读 验证和序列化 文档。

¥To learn more, read the Validation and Serialization documentation.

getSchemas

fastify.getSchemas(),返回通过 .addSchema 添加的所有模式的哈希值。哈希的键是提供的 JSON 模式的 $id

¥fastify.getSchemas(), returns a hash of all schemas added via .addSchema. The keys of the hash are the $ids of the JSON Schema provided.

getSchema

fastify.getSchema(id),返回使用 .addSchema 和匹配的 id 添加的 JSON 模式。如果未找到,则返回 undefined

¥fastify.getSchema(id), return the JSON schema added with .addSchema and the matching id. It returns undefined if it is not found.

setReplySerializer

为所有路由设置响应序列化器。如果未设置 Reply.serializer(func),则将默认使用它。处理程序是完全封装的,因此不同的插件可以设置不同的错误处理程序。注意:仅针对状态 2xx 调用函数参数。查看 setErrorHandler 以了解错误。

¥Set the reply serializer for all the routes. This will be used as default if a Reply.serializer(func) has not been set. The handler is fully encapsulated, so different plugins can set different error handlers. Note: the function parameter is called only for status 2xx. Check out the setErrorHandler for errors.

fastify.setReplySerializer(function (payload, statusCode){
// serialize the payload with a sync function
return `my serialized ${statusCode} content: ${payload}`
})

setValidatorCompiler

为所有路由设置模式验证器编译器。参见 #schema-validator

¥Set the schema validator compiler for all routes. See #schema-validator.

setSchemaErrorFormatter

为所有路由设置架构错误格式化程序。参见 #error-handling

¥Set the schema error formatter for all routes. See #error-handling.

setSerializerCompiler

为所有路由设置模式序列化器编译器。参见 #schema-serializer

¥Set the schema serializer compiler for all routes. See #schema-serializer.

注意 如果设置,setReplySerializer 具有优先级!

¥setReplySerializer has priority if set!

validatorCompiler

此属性可用于获取模式验证器。如果未设置,它将是 null,直到服务器启动,然后它将是一个具有签名 function ({ schema, method, url, httpPart }) 的函数,该函数返回编译为用于验证数据的函数的输入 schema。输入 schema 可以访问使用 .addSchema 函数添加的所有共享模式。

¥This property can be used to get the schema validator. If not set, it will be null until the server starts, then it will be a function with the signature function ({ schema, method, url, httpPart }) that returns the input schema compiled to a function for validating data. The input schema can access all the shared schemas added with .addSchema function.

serializerCompiler

此属性可用于获取架构序列化器。如果未设置,它将是 null,直到服务器启动,然后它将是一个具有签名 function ({ schema, method, url, httpPart }) 的函数,该函数返回编译为用于验证数据的函数的输入 schema。输入 schema 可以访问使用 .addSchema 函数添加的所有共享模式。

¥This property can be used to get the schema serializer. If not set, it will be null until the server starts, then it will be a function with the signature function ({ schema, method, url, httpPart }) that returns the input schema compiled to a function for validating data. The input schema can access all the shared schemas added with .addSchema function.

schemaErrorFormatter

此属性可用于设置一个函数来格式化 validationCompiler 无法验证架构时发生的错误。参见 #error-handling

¥This property can be used to set a function to format errors that happen while the validationCompiler fails to validate the schema. See #error-handling.

schemaController

该属性可用于完全管理:

¥This property can be used to fully manage:

  • bucket:应用架构的存储位置

    ¥bucket: where the schemas of your application will be stored

  • compilersFactory:哪个模块必须编译 JSON 模式

    ¥compilersFactory: what module must compile the JSON schemas

当你的模式存储在 Fastify 未知的另一个数据结构中时,它会很有用。

¥It can be useful when your schemas are stored in another data structure that is unknown to Fastify.

另一个用例是调整所有模式处理。这样做可以使用 Ajv v8 JTD 或独立功能。要使用 JTD 或独立模式,请参阅 @fastify/ajv-compiler 文档

¥Another use case is to tweak all the schemas processing. Doing so it is possible to use Ajv v8 JTD or Standalone feature. To use such as JTD or the Standalone mode, refers to the @fastify/ajv-compiler documentation.

const fastify = Fastify({
schemaController: {
/**

* This factory is called whenever `fastify.register()` is called.

* It may receive as input the schemas of the parent context if some schemas have been added.

* @param {object} parentSchemas these schemas will be returned by the

* `getSchemas()` method function of the returned `bucket`.
*/
bucket: function factory (parentSchemas) {
return {
add (inputSchema) {
// This function must store the schema added by the user.
// This function is invoked when `fastify.addSchema()` is called.
},
getSchema (schema$id) {
// This function must return the raw schema requested by the `schema$id`.
// This function is invoked when `fastify.getSchema(id)` is called.
return aSchema
},
getSchemas () {
// This function must return all the schemas referenced by the routes schemas' $ref
// It must return a JSON where the property is the schema `$id` and the value is the raw JSON Schema.
const allTheSchemaStored = {
'schema$id1': schema1,
'schema$id2': schema2
}
return allTheSchemaStored
}
}
},

/**

* The compilers factory lets you fully control the validator and serializer

* in the Fastify's lifecycle, providing the encapsulation to your compilers.
*/
compilersFactory: {
/**

* This factory is called whenever a new validator instance is needed.

* It may be called whenever `fastify.register()` is called only if new schemas have been added to the

* encapsulation context.

* It may receive as input the schemas of the parent context if some schemas have been added.

* @param {object} externalSchemas these schemas will be returned by the

* `bucket.getSchemas()`. Needed to resolve the external references $ref.

* @param {object} ajvServerOption the server `ajv` options to build your compilers accordingly
*/
buildValidator: function factory (externalSchemas, ajvServerOption) {
// This factory function must return a schema validator compiler.
// See [#schema-validator](./Validation-and-Serialization.md#schema-validator) for details.
const yourAjvInstance = new Ajv(ajvServerOption.customOptions)
return function validatorCompiler ({ schema, method, url, httpPart }) {
return yourAjvInstance.compile(schema)
}
},

/**

* This factory is called whenever a new serializer instance is needed.

* It may be called whenever `fastify.register()` is called only if new schemas have been added to the

* encapsulation context.

* It may receive as input the schemas of the parent context if some schemas have been added.

* @param {object} externalSchemas these schemas will be returned by the

* `bucket.getSchemas()`. Needed to resolve the external references $ref.

* @param {object} serializerOptsServerOption the server `serializerOpts`

* options to build your compilers accordingly
*/
buildSerializer: function factory (externalSchemas, serializerOptsServerOption) {
// This factory function must return a schema serializer compiler.
// See [#schema-serializer](./Validation-and-Serialization.md#schema-serializer) for details.
return function serializerCompiler ({ schema, method, url, httpStatus, contentType }) {
return data => JSON.stringify(data)
}
}
}
}
});

setNotFoundHandler

fastify.setNotFoundHandler(handler(request, reply)):设置 404 处理程序。此调用由前缀封装,因此如果将不同的 prefix 选项 传递给 fastify.register(),则不同的插件可以设置不同的未找到处理程序。处理程序被视为常规路由处理程序,因此请求将通过完整的 Fastify 生命周期。还支持 async-await。

¥fastify.setNotFoundHandler(handler(request, reply)): set the 404 handler. This call is encapsulated by prefix, so different plugins can set different not found handlers if a different prefix option is passed to fastify.register(). The handler is treated as a regular route handler so requests will go through the full Fastify lifecycle. async-await is supported as well.

你还可以为 404 处理程序注册 preValidationpreHandler 钩子。

¥You can also register preValidation and preHandler hooks for the 404 handler.

注意 使用此方法注册的 preValidation 钩子将针对 Fastify 无法识别的路由运行,而不是在路由处理程序手动调用 reply.callNotFound 时运行。在这种情况下,只会运行 preHandler。

¥The preValidation hook registered using this method will run for a route that Fastify does not recognize and not when a route handler manually calls reply.callNotFound. In which case, only preHandler will be run.

fastify.setNotFoundHandler({
preValidation: (req, reply, done) => {
// your code
done()
},
preHandler: (req, reply, done) => {
// your code
done()
}
}, function (request, reply) {
// Default not found handler with preValidation and preHandler hooks
})

fastify.register(function (instance, options, done) {
instance.setNotFoundHandler(function (request, reply) {
// Handle not found request without preValidation and preHandler hooks
// to URLs that begin with '/v1'
})
done()
}, { prefix: '/v1' })

Fastify 在注册插件之前调用 setNotFoundHandler 在启动时添加默认的 404 处理程序。如果你想要增强默认 404 处理程序的行为,例如使用插件,你可以在这些注册插件的上下文中调用不带参数 fastify.setNotFoundHandler() 的 setNotFoundHandler。

¥Fastify calls setNotFoundHandler to add a default 404 handler at startup before plugins are registered. If you would like to augment the behavior of the default 404 handler, for example with plugins, you can call setNotFoundHandler with no arguments fastify.setNotFoundHandler() within the context of these registered plugins.

注意 请求对象的某些配置属性在自定义未找到处理程序中未定义。例如。:request.routerPathrouterMethodcontext.config。该方法的设计目标是允许调用常见的未找到路由。要返回每个路由自定义的 404 响应,你可以在响应本身中执行此操作。

¥Some config properties from the request object will be undefined inside the custom not found handler. E.g.: request.routerPath, routerMethod and context.config. This method design goal is to allow calling the common not found route. To return a per-route customized 404 response, you can do it in the response itself.

setErrorHandler

fastify.setErrorHandler(handler(error, request, reply)):设置一个在发生错误时将被调用的函数。该处理程序绑定到 Fastify 实例并完全封装,因此不同的插件可以设置不同的错误处理程序。还支持 async-await。

¥fastify.setErrorHandler(handler(error, request, reply)): Set a function that will be called whenever an error happens. The handler is bound to the Fastify instance and is fully encapsulated, so different plugins can set different error handlers. async-await is supported as well.

如果错误 statusCode 小于 400,Fastify 会在调用错误处理程序之前自动将其设置为 500。

¥If the error statusCode is less than 400, Fastify will automatically set it to 500 before calling the error handler.

setErrorHandler 不会捕获:

¥setErrorHandler will not catch:

  • onResponse 钩子中抛出错误,因为响应已经发送给客户端。改用 onSend 钩子。

    ¥errors thrown in an onResponse hook because the response has already been sent to the client. Use the onSend hook instead.

  • 未找到 (404) 错误。改用 setNotFoundHandler

    ¥not found (404) errors. Use setNotFoundHandler instead.

fastify.setErrorHandler(function (error, request, reply) {
// Log error
this.log.error(error)
// Send error response
reply.status(409).send({ ok: false })
})

Fastify 提供了一个默认函数,如果未设置错误处理程序,则会调用该函数。可以使用 fastify.errorHandler 访问它,并根据其 statusCode 记录错误。

¥Fastify is provided with a default function that is called if no error handler is set. It can be accessed using fastify.errorHandler and it logs the error with respect to its statusCode.

const statusCode = error.statusCode
if (statusCode >= 500) {
log.error(error)
} else if (statusCode >= 400) {
log.info(error)
} else {
log.error(error)
}

setChildLoggerFactory

fastify.setChildLoggerFactory(factory(logger, bindings, opts, rawReq)):设置一个函数,在为每个请求创建子日志器实例时将调用该函数,该函数允许修改或添加子日志器绑定和日志器选项,或返回自定义子日志器实现。

¥fastify.setChildLoggerFactory(factory(logger, bindings, opts, rawReq)): Set a function that will be called when creating a child logger instance for each request which allows for modifying or adding child logger bindings and logger options, or returning a custom child logger implementation.

子日志器绑定比每个日志绑定具有性能优势,因为它们是在创建子日志器时由 Pino 预序列化的。

¥Child logger bindings have a performance advantage over per-log bindings because they are pre-serialized by Pino when the child logger is created.

第一个参数是父日志器实例,后面是应传递给子日志器的默认绑定和日志器选项,最后是原始请求(不是 Fastify 请求对象)。该函数与 this 绑定,this 是 Fastify 实例。

¥The first parameter is the parent logger instance, followed by the default bindings and logger options which should be passed to the child logger, and finally the raw request (not a Fastify request object). The function is bound with this being the Fastify instance.

例如:

¥For example:

const fastify = require('fastify')({
childLoggerFactory: function (logger, bindings, opts, rawReq) {
// Calculate additional bindings from the request if needed
bindings.traceContext = rawReq.headers['x-cloud-trace-context']
return logger.child(bindings, opts)
}
})

该处理程序绑定到 Fastify 实例并完全封装,因此不同的插件可以设置不同的日志器工厂。

¥The handler is bound to the Fastify instance and is fully encapsulated, so different plugins can set different logger factories.

setGenReqId

fastify.setGenReqId(function (rawReq)) 用于设置其他 Fastify 实例的请求 ID 的同步函数。它将接收原始传入请求作为参数。提供的函数在任何情况下都不应抛出错误。

¥fastify.setGenReqId(function (rawReq)) Synchronous function for setting the request-id for additional Fastify instances. It will receive the raw incoming request as a parameter. The provided function should not throw an Error in any case.

特别是在分布式系统中,你可能希望覆盖默认 ID 生成行为以处理生成不同 ID 的自定义方式,以便处理不同的用例。例如可观察性或 webhook 插件。

¥Especially in distributed systems, you may want to override the default ID generation behavior to handle custom ways of generating different IDs in order to handle different use cases. Such as observability or webhooks plugins.

例如:

¥For example:

const fastify = require('fastify')({
genReqId: (req) => {
return 'base'
}
})

fastify.register((instance, opts, done) => {
instance.setGenReqId((req) => {
// custom request ID for `/webhooks`
return 'webhooks-id'
})
done()
}, { prefix: '/webhooks' })

fastify.register((instance, opts, done) => {
instance.setGenReqId((req) => {
// custom request ID for `/observability`
return 'observability-id'
})
done()
}, { prefix: '/observability' })

处理程序绑定到 Fastify 实例并完全封装,因此不同的插件可以设置不同的请求 ID。

¥The handler is bound to the Fastify instance and is fully encapsulated, so different plugins can set a different request ID.

addConstraintStrategy

添加自定义约束策略的功能。要注册新类型的约束,你必须添加一个新的约束策略,该策略知道如何将值与处理程序相匹配,并且知道如何从请求中获取约束值。

¥Function to add a custom constraint strategy. To register a new type of constraint, you must add a new constraint strategy that knows how to match values to handlers, and that knows how to get the constraint value from a request.

使用 fastify.addConstraintStrategy 方法添加自定义约束策略:

¥Add a custom constraint strategy using the fastify.addConstraintStrategy method:

const customResponseTypeStrategy = {
// strategy name for referencing in the route handler `constraints` options
name: 'accept',
// storage factory for storing routes in the find-my-way route tree
storage: function () {
let handlers = {}
return {
get: (type) => { return handlers[type] || null },
set: (type, store) => { handlers[type] = store }
}
},
// function to get the value of the constraint from each incoming request
deriveConstraint: (req, ctx) => {
return req.headers['accept']
},
// optional flag marking if handlers without constraints can match requests that have a value for this constraint
mustMatchWhenDerived: true
}

const router = Fastify();
router.addConstraintStrategy(customResponseTypeStrategy);

hasConstraintStrategy

fastify.hasConstraintStrategy(strategyName) 检查是否已经存在同名的自定义约束策略。

¥The fastify.hasConstraintStrategy(strategyName) checks if there already exists a custom constraint strategy with the same name.

printRoutes

fastify.printRoutes():Fastify 路由为每个 HTTP 方法构建一个路由树。如果你调用 PrettyPrint 而不指定 HTTP 方法,它会将所有树合并为一棵并打印它。合并树并不代表内部路由结构。不要用它来调试。

¥fastify.printRoutes(): Fastify router builds a tree of routes for each HTTP method. If you call the prettyPrint without specifying an HTTP method, it will merge all the trees into one and print it. The merged tree doesn't represent the internal router structure. Do not use it for debugging.

请记住在 ready 调用内部或之后调用它。

¥Remember to call it inside or after a ready call.

fastify.get('/test', () => {})
fastify.get('/test/hello', () => {})
fastify.get('/testing', () => {})
fastify.get('/testing/:param', () => {})
fastify.put('/update', () => {})

fastify.ready(() => {
console.log(fastify.printRoutes())
// └── /
// ├── test (GET)
// │ ├── /hello (GET)
// │ └── ing (GET)
// │ └── /
// │ └── :param (GET)
// └── update (PUT)
})

如果你想打印内部路由树,你应该指定 method 参数。打印的树将代表内部路由结构。你可以将其用于调试。

¥If you want to print the internal router tree, you should specify the method param. Printed tree will represent the internal router structure. You can use it for debugging.

  console.log(fastify.printRoutes({ method: 'GET' }))
// └── /
// └── test (GET)
// ├── /hello (GET)
// └── ing (GET)
// └── /
// └── :param (GET)

console.log(fastify.printRoutes({ method: 'PUT' }))
// └── /
// └── update (PUT)

fastify.printRoutes({ commonPrefix: false }) 将打印压缩树。当你有大量具有公共前缀的路由时,这可能很有用。它并不代表路由的内部结构。不要用它来调试。

¥fastify.printRoutes({ commonPrefix: false }) will print compressed trees. This may be useful when you have a large number of routes with common prefixes. It doesn't represent the internal router structure. Do not use it for debugging.

  console.log(fastify.printRoutes({ commonPrefix: false }))
// ├── /test (GET)
// │ ├── /hello (GET)
// │ └── ing (GET)
// │ └── /:param (GET)
// └── /update (PUT)

fastify.printRoutes({ includeMeta: (true | []) }) 将显示每个显示路由的 route.store 对象的属性。这可以是键的 array(例如 ['onRequest', Symbol('key')]),也可以是 true 以显示所有属性。简写选项,fastify.printRoutes({ includeHooks: true }) 将包含所有 hooks

¥fastify.printRoutes({ includeMeta: (true | []) }) will display properties from the route.store object for each displayed route. This can be an array of keys (e.g. ['onRequest', Symbol('key')]), or true to display all properties. A shorthand option, fastify.printRoutes({ includeHooks: true }) will include all hooks.

  fastify.get('/test', () => {})
fastify.get('/test/hello', () => {})

const onTimeout = () => {}

fastify.addHook('onRequest', () => {})
fastify.addHook('onTimeout', onTimeout)

console.log(fastify.printRoutes({ includeHooks: true, includeMeta: ['errorHandler'] }))
// └── /
// └── test (GET)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// • (errorHandler) "defaultErrorHandler()"
// test (HEAD)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// • (onSend) ["headRouteOnSendHandler()"]
// • (errorHandler) "defaultErrorHandler()"
// └── /hello (GET)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// • (errorHandler) "defaultErrorHandler()"
// /hello (HEAD)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// • (onSend) ["headRouteOnSendHandler()"]
// • (errorHandler) "defaultErrorHandler()"

console.log(fastify.printRoutes({ includeHooks: true }))
// └── /
// └── test (GET)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// test (HEAD)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// • (onSend) ["headRouteOnSendHandler()"]
// └── /hello (GET)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// /hello (HEAD)
// • (onTimeout) ["onTimeout()"]
// • (onRequest) ["anonymous()"]
// • (onSend) ["headRouteOnSendHandler()"]

printPlugins

fastify.printPlugins():打印 avvio 使用的内部插件树的表示,对于调试需求顺序问题很有用。

¥fastify.printPlugins(): Prints the representation of the internal plugin tree used by the avvio, useful for debugging require order issues.

请记住在 ready 调用内部或之后调用它。

¥Remember to call it inside or after a ready call.

fastify.register(async function foo (instance) {
instance.register(async function bar () {})
})
fastify.register(async function baz () {})

fastify.ready(() => {
console.error(fastify.printPlugins())
// will output the following to stderr:
// └── root
// ├── foo
// │ └── bar
// └── baz
})

addContentTypeParser

fastify.addContentTypeParser(content-type, options, parser) 用于传递给定内容类型的自定义解析器。用于添加自定义内容类型的解析器,例如 text/json, application/vnd.oasis.opendocument.textcontent-type 可以是字符串、字符串数组或 RegExp。

¥fastify.addContentTypeParser(content-type, options, parser) is used to pass a custom parser for a given content type. Useful for adding parsers for custom content types, e.g. text/json, application/vnd.oasis.opendocument.text. content-type can be a string, string array or RegExp.

// The two arguments passed to getDefaultJsonParser are for ProtoType poisoning
// and Constructor Poisoning configuration respectively. The possible values are
// 'ignore', 'remove', 'error'. ignore skips all validations and it is similar
// to calling JSON.parse() directly. See the
// [`secure-json-parse` documentation](https://github.com/fastify/secure-json-parse#api) for more information.

fastify.addContentTypeParser('text/json', { asString: true }, fastify.getDefaultJsonParser('ignore', 'ignore'))

hasContentTypeParser

fastify.hasContentTypeParser(contentType) 用于检查当前上下文中是否存在指定内容类型的内容类型解析器。

¥fastify.hasContentTypeParser(contentType) is used to check whether there is a content type parser in the current context for the specified content type.

fastify.hasContentTypeParser('text/json')

fastify.hasContentTypeParser(/^.+\/json$/)

removeContentTypeParser

fastify.removeContentTypeParser(contentType) 用于删除当前上下文中的内容类型解析器。例如,此方法允许删除 application/jsontext/plain 的两个内置解析器。

¥fastify.removeContentTypeParser(contentType) is used to remove content type parsers in the current context. This method allows for example to remove the both built-in parsers for application/json and text/plain.

fastify.removeContentTypeParser('application/json')

fastify.removeContentTypeParser(['application/json', 'text/plain'])

removeAllContentTypeParsers

fastify.removeAllContentTypeParsers() 方法允许删除当前上下文中的所有内容类型解析器。此方法的一个用例是捕获所有内容类型解析器的实现。在使用 fastify.addContentTypeParser() 添加此解析器之前,可以调用 removeAllContentTypeParsers 方法。

¥The fastify.removeAllContentTypeParsers() method allows all content type parsers in the current context to be removed. A use case of this method is the implementation of catch-all content type parser. Before adding this parser with fastify.addContentTypeParser() one could call the removeAllContentTypeParsers method.

有关不同内容类型解析器 API 用法的更多详细信息,请参阅 此处

¥For more details about the usage of the different content type parser APIs see here.

getDefaultJsonParser

fastify.getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning) 需要两个参数。第一个参数是 ProtoType 中毒配置,第二个参数是构造函数中毒配置。有关更多信息,请参阅 secure-json-parse 文档

¥fastify.getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning) takes two arguments. First argument is ProtoType poisoning configuration and second argument is constructor poisoning configuration. See the secure-json-parse documentation for more information.

defaultTextParser

fastify.defaultTextParser() 可用于将内容解析为纯文本。

¥fastify.defaultTextParser() can be used to parse content as plain text.

fastify.addContentTypeParser('text/json', { asString: true }, fastify.defaultTextParser)

errorHandler

fastify.errorHandler 可用于使用 fastify 的默认错误处理程序来处理错误。

¥fastify.errorHandler can be used to handle errors using fastify's default error handler.

fastify.get('/', {
errorHandler: (error, request, reply) => {
if (error.code === 'SOMETHING_SPECIFIC') {
reply.send({ custom: 'response' })
return
}

fastify.errorHandler(error, request, response)
}
}, handler)

childLoggerFactory

fastify.childLoggerFactory 返回 Fastify 实例的自定义日志器工厂函数。有关更多信息,请参阅 childLoggerFactory 配置选项

¥fastify.childLoggerFactory returns the custom logger factory function for the Fastify instance. See the childLoggerFactory config option for more info.

Symbol.asyncDispose

fastify[Symbol.asyncDispose] 是一个符号,可用于定义一个异步函数,该函数将在 Fastify 实例关闭时调用。

¥fastify[Symbol.asyncDispose] is a symbol that can be used to define an asynchronous function that will be called when the Fastify instance is closed.

它通常与 using TypeScript 关键字一起使用,以确保在关闭 Fastify 实例时清理资源。

¥It's commonly used alongside the using TypeScript keyword to ensure that resources are cleaned up when the Fastify instance is closed.

这在短期进程或单元测试中完美结合,你必须在从函数内部返回后关闭所有 Fastify 资源。

¥This combines perfectly inside short lived processes or unit tests, where you must close all Fastify resources after returning from inside the function.

test('Uses app and closes it afterwards', async () => {
await using app = fastify();
// do something with app.
})

在上面的例子中,Fastify 在测试完成后自动关闭。

¥In the above example, Fastify is closed automatically after the test finishes.

阅读有关 TypeScript 5.2 中引入的 ECMAScript Explicit Resource Management使用关键字 的更多信息。

¥Read more about the ECMAScript Explicit Resource Management and the using keyword introduced in TypeScript 5.2.

initialConfig

fastify.initialConfig:暴露一个冻结的只读对象,注册用户传递给 Fastify 实例的初始选项。

¥fastify.initialConfig: Exposes a frozen read-only object registering the initial options passed down by the user to the Fastify instance.

目前可以公开的属性有:

¥The properties that can currently be exposed are:

  • connectionTimeout

  • keepAliveTimeout

  • bodyLimit

  • caseSensitive

  • allowUnsafeRegex

  • http2

  • https(如果明确传递,它将返回 false/true{ allowHTTP1: true/false }

    ¥https (it will return false/true or { allowHTTP1: true/false } if explicitly passed)

  • ignoreTrailingSlash

  • disableRequestLogging

  • maxParamLength

  • onProtoPoisoning

  • onConstructorPoisoning

  • pluginTimeout

  • requestIdHeader

  • requestIdLogLabel

  • http2SessionTimeout

  • useSemicolonDelimiter

const { readFileSync } = require('node:fs')
const Fastify = require('fastify')

const fastify = Fastify({
https: {
allowHTTP1: true,
key: readFileSync('./fastify.key'),
cert: readFileSync('./fastify.cert')
},
logger: { level: 'trace'},
ignoreTrailingSlash: true,
maxParamLength: 200,
caseSensitive: true,
trustProxy: '127.0.0.1,192.168.1.1/24',
})

console.log(fastify.initialConfig)
/*
will log :
{
caseSensitive: true,
https: { allowHTTP1: true },
ignoreTrailingSlash: true,
maxParamLength: 200
}
*/

fastify.register(async (instance, opts) => {
instance.get('/', async (request, reply) => {
return instance.initialConfig
/*
will return :
{
caseSensitive: true,
https: { allowHTTP1: true },
ignoreTrailingSlash: true,
maxParamLength: 200
}
*/
})

instance.get('/error', async (request, reply) => {
// will throw an error because initialConfig is read-only
// and can not be modified
instance.initialConfig.https.allowHTTP1 = false

return instance.initialConfig
})
})

// Start listening.
fastify.listen({ port: 3000 }, (err) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})