99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

Fastify 中間件

2020-02-06 15:38 更新

中間件

Fastify 提供了一個開箱即用的異步中間件引擎。它兼容 Express 與 Restify 的中間件。

想知道中間件何時執(zhí)行,請看生命周期一文。

Fastify 的中間件不支持 middleware(err, req, res, next) 這一完整語法,因為錯誤在 Fastify 內(nèi)部就被解決了。 此外,Express 和 Restify 添加在 req 和 res 對象之上的方法,F(xiàn)astify 也不支持。

假如你使用一個打包了多個更小的中間件的中間件,例如 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')())

或者,在這個 helmet 的例子中,你可以使用針對 Fastify 和 helmet 的整合做了優(yōu)化的 fastify-helmet 插件

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

fastify.register(helmet)

請記住,中間件能被封裝。這就意味著你可以通過使用 register 來決定中間件該在何處運行,正如插件指南一文所述。

Fastify 中間件不會暴露 send 等 Fastify 的 Reply 實例上專屬的方法。這是因為,雖然 Fastify 使用 Request 和 Reply 對象包裹了 Node 原生的 req 和 res 實例,但是它們的處理要在中間件階段之后。因此,在一個中間件里,你必須使用 Node 原生的 req 和 res 對象。要使用 Fastify 的 Request 與 Reply 實例,你可以通過 preHandler 鉤子。更多信息,請看鉤子

將中間件限定在特定的路徑執(zhí)行

如果你只想在某些路徑下運行一個中間件,只需將路徑作為 use 的第一個參數(shù)傳遞即可!

注意,該做法不支持參數(shù)路由 (例如:/user/:id/comments),且在多個路徑中不能使用通配符。

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

// 單個路徑
fastify.use('/css', serveStatic(path.join(__dirname, '/assets')))

// 通配符路徑
fastify.use('/css/*', serveStatic(path.join(__dirname, '/assets')))

// 多個路徑
fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')))

Express 中間件兼容性

Express 很大程度上修改了 Node 原生的 Request 和 Response 對象,所以 Fastify 無法確保中間件一定完全兼容。一些 Express 特殊的功能,例如 res.sendFile()、res.send() 或者 express.Router() 的實例將無法在 Fastify 中正常工作。舉個例子,cors 可以正常兼容但是 passport 就不可以。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號