Skip to main content

中间件

中间件

¥Middleware

从 Fastify v3.0.0 开始,中间件不支持开箱即用,需要外部插件,如 @fastify/express@fastify/middie

¥Starting with Fastify v3.0.0, middleware is not supported out of the box and requires an external plugin such as @fastify/express or @fastify/middie.

@fastify/express 插件注册到 use Express 中间件的示例:

¥An example of registering the @fastify/express plugin to use Express middleware:

await fastify.register(require('@fastify/express'))
fastify.use(require('cors')())
fastify.use(require('dns-prefetch-control')())
fastify.use(require('frameguard')())
fastify.use(require('hsts')())
fastify.use(require('ienoopen')())
fastify.use(require('x-xss-protection')())

@fastify/middie 也可以使用,它为简单的 Express 风格中间件提供支持,并提高性能:

¥@fastify/middie can also be used, which provides support for simple Express-style middleware with improved performance:

await fastify.register(require('@fastify/middie'))
fastify.use(require('cors')())

中间件可以封装,允许使用 register 控制其运行位置,如 插件指南 中所述。

¥Middleware can be encapsulated, allowing control over where it runs using register as explained in the plugins guide.

Fastify 中间件不公开 send 方法或特定于 Fastify 响应 实例的其他方法。这是因为 Fastify 在内部使用 请求响应 对象封装传入的 reqres Node 实例,但这是在中间件阶段之后完成的。要创建中间件,请使用 Node reqres 实例。或者,使用已经具有 Fastify 请求响应 实例的 preHandler 钩子。有关更多信息,请参阅 钩子

¥Fastify middleware does not expose the send method or other methods specific to the Fastify Reply instance. This is because Fastify wraps the incoming req and res Node instances using the Request and Reply objects internally, but this is done after the middleware phase. To create middleware, use the Node req and res instances. Alternatively, use the preHandler hook that already has the Fastify Request and Reply instances. For more information, see Hooks.

限制中间件执行到某些路径

¥Restrict middleware execution to certain paths

要在特定路径下运行中间件,请将路径作为第一个参数传递给 use

¥To run middleware under certain paths, pass the path as the first parameter to use.

🛈 注意:这不支持带参数的路由(例如 /user/:id/comments),并且不支持多条路径中的通配符。

¥🛈 Note: This does not support routes with parameters (e.g. /user/:id/comments) and wildcards are not supported in multiple paths.

const path = require('node:path')
const serveStatic = require('serve-static')

// Single path
fastify.use('/css', serveStatic(path.join(__dirname, '/assets')))

// Wildcard path
fastify.use('/css/(.*)', serveStatic(path.join(__dirname, '/assets')))

// Multiple paths
fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')))

替代品

¥Alternatives

Fastify 提供了常用中间件的替代方案,例如 helmet@fastify/helmetcors@fastify/corsserve-static@fastify/static

¥Fastify offers alternatives to commonly used middleware, such as @fastify/helmet for helmet, @fastify/cors for cors, and @fastify/static for serve-static.