中间件
中间件
¥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 风格中间件,但性能有所提高:
¥You can also use @fastify/middie
, which provides
support for simple Express-style middleware but with improved performance:
await fastify.register(require('@fastify/middie'))
fastify.use(require('cors')())
请记住,中间件是可以封装的;这意味着你可以使用 register
决定中间件应该在哪里运行,如 插件指南 中所述。
¥Remember that middleware can be encapsulated; this means that you can decide
where your middleware should run by using register
as explained in the
plugins guide.
Fastify 中间件不公开 send
方法或特定于 Fastify 响应 实例的其他方法。这是因为 Fastify 在内部使用 请求 和 响应 对象封装传入的 req
和 res
Node 实例,但这是在中间件阶段之后完成的。如果你需要创建中间件,则必须使用 Node req
和 res
实例。否则,你可以使用已经具有 请求 和 响应 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. If you need to create
middleware, you have to use the Node req
and res
instances. Otherwise, you
can use the preHandler
hook that already has the
Request and Reply Fastify instances.
For more information, see Hooks.
限制中间件执行到某些路径
¥Restrict middleware execution to certain paths
如果你只需要在某些路径下运行中间件,只需将路径作为第一个参数传递给 use
即可!
¥If you need to only run middleware under certain paths, just pass the path as
the first parameter to use
and you are done!
请注意,这不支持带参数的路由(例如 /user/:id/comments
),并且多路径中不支持通配符。
¥Note that 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/helmet
、cors
的 @fastify/cors
和 serve-static
的 @fastify/static
。
¥Fastify offers some alternatives to the most commonly used middleware, such as
@fastify/helmet
in case of
helmet
,
@fastify/cors
for
cors
, and
@fastify/static
for
serve-static
.