中间件

Fastify 提供了与 ExpressRestify 中间件兼容的异步中间件引擎

如果你需要通过视觉反馈来了解执行中间件的时间,请查看生命周期

Fastify 不支持错误处理中间件(err,req,res,next)语法,因为在 Fastify 已经完成了错误处理的功能。

此外,如果使用的中间件中(如helmet)捆绑了其他的小型中间件,我们建议使用单个模块来获得更好的性能。

fastify.use(require('cors')())
fastify.use(require('dns-prefetch-control')())
fastify.use(require('frameguard')())
fastify.use(require('hide-powered-by')())
fastify.use(require('hsts')())
fastify.use(require('ienoopen')())
fastify.use(require('x-xss-protection')())

或者,可以使用 fastify-helmet 插件。

const fastify = require('fastify')()
const helmet = require('fastify-helmet')

fastify.register(helmet)

记住,中间件可以被封装,意味着可以通过register的位置决定你的中间件在何处执行。

Fastify 中间件不会暴露 send 和一些特定的方法到 Reply 实例上。因为 Fastify 内部使用了自己的 RequestReply 对象包装了 Nodejs 的 reqres ,但这是在中间阶段之后完成的。如果想创建一个中间件,则必须使用 Nodejs 的reqres 实例。或者可以使用具有 RequestReply 实例的 preHandler 钩子。 查看 钩子函数

将中间件的执行限制到某个路由

如果想要在特定路由下运行中间件,可以将路径作为第一个参数传入 use 即可完成!

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

const serveStatic = require('serve-static')

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

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

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

results matching ""

    No results matching ""