yuheng/doc/fastify-docs/docs/Middleware.md
2025-03-19 15:54:28 +08:00

29 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<h1 align="center">Fastify</h1>
## 中间件
从 3.0.0 版本开始Fastify 便不再内建地支持中间件了,你需要通过插件例如 [`fastify-express`](https://github.com/fastify/fastify-express) 或 [`middie`](https://github.com/fastify/middie) 来使用它们。
以下是通过 [`fastify-express`](https://github.com/fastify/fastify-express) 插件,来使用 express 中间件的示例:
```js
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")());
```
或者通过 [`middie`](https://github.com/fastify/middie),它提供了对简单的 express 风格的中间件的支持,但性能更佳:
```js
await fastify.register(require("middie"));
fastify.use(require("cors")());
```
### 替代
Fastify 提供了最常用中间件的替代品,例如:[`fastify-helmet`](https://github.com/fastify/fastify-helmet) 之于 [`helmet`](https://github.com/helmetjs/helmet)[`fastify-cors`](https://github.com/fastify/fastify-cors) 之于 [`cors`](https://github.com/expressjs/cors),以及 [`fastify-static`](https://github.com/fastify/fastify-static) 之于 [`serve-static`](https://github.com/expressjs/serve-static)。