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

中介層

中介層

從 Fastify v3.0.0 開始,中介層不再直接支援,需要使用外部外掛程式,例如 @fastify/express@fastify/middie

以下是註冊 @fastify/express 外掛程式以 use Express 中介層的範例

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 風格中介層的支援,但具有更高的效能

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

請記住,中介層可以被封裝;這表示您可以決定中介層應該在哪裡運行,方法是使用 外掛程式指南 中說明的 register

Fastify 中介層不會公開 send 方法或其他特定於 Fastify Reply 實例的方法。這是因為 Fastify 會在內部使用 RequestReply 物件封裝傳入的 reqres Node 實例,但這是在中介層階段之後完成的。如果您需要建立中介層,則必須使用 Node reqres 實例。否則,您可以使用已經有 RequestReply Fastify 實例的 preHandler 鉤子。有關更多資訊,請參閱鉤子

限制中介層執行於特定路徑

如果您只需要在特定路徑下執行中介層,只需將路徑作為第一個參數傳遞給 use 就完成了!

請注意,這不支援帶有參數的路由(例如 /user/:id/comments),並且多個路徑中不支援萬用字元。

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

替代方案

Fastify 為最常用的中介層提供了一些替代方案,例如,對於 helmet,可以使用 @fastify/helmet;對於 cors,可以使用 @fastify/cors;而對於 serve-static,可以使用 @fastify/static