多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## Helmet 通过适当地设置 `HTTP` 头,[Helmet](https://github.com/helmetjs/helmet) 可以帮助保护您的应用免受一些众所周知的 `Web` 漏洞的影响。通常,`Helmet` 只是`14`个较小的中间件函数的集合,它们设置与安全相关的 `HTTP` 头([阅读更多](https://github.com/helmetjs/helmet#how-it-works))。 > 要在全局使用`Helmet`,需要在调用`app.use()`之前或者可能调用`app.use()`函数之前注册。这是由平台底层机制中(EXpress或者Fastify)中间件/路径的定义决定的。如果在定义路径之后使用`helmet`或者`cors`中间件,其之前的路径将不会应用这些中间件,而仅在定义之后的路径中应用。 ### 在Express中使用(默认) 首先,安装所需的包: ```bash $ npm i --save helmet ``` 安装完成后,将其应用为全局中间件。 ```typescript import * as helmet from 'helmet'; // somewhere in your initialization file app.use(helmet()); ``` > 如果在引入`helmet`时返回`This expression is not callable`错误。你可能需要将项目中`tsconfig.json`文件的`allowSyntheticDefaultImports`和`esModuleInterop`选项配置为`true`。在这种情况下,将引入声明修改为:`import helmet from 'helmet'`。 ### 在Fastify中使用 如果使用`FastifyAdapter`,安装`fastify-helmet`包: ```bash $ npm i --save fastify-helmet ``` `fastify-helmet`需要作为`Fastify`插件而不是中间件使用,例如,用`app.register()`调用。 ```typescript import * as helmet from 'fastify-helmet'; // somewhere in your initialization file app.register(helmet); ``` > 在使用`apollo-server-fastify`和`fastify-helmet`时,在`GraphQL`应用中与[CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)使用时可能出问题,需要如下配置CSP。 ```TypeScript app.register(helmet, { contentSecurityPolicy: { directives: { defaultSrc: [`'self'`], styleSrc: [`'self'`, `'unsafe-inline'`, 'cdn.jsdelivr.net', 'fonts.googleapis.com'], fontSrc: [`'self'`, 'fonts.gstatic.com'], imgSrc: [`'self'`, 'data:', 'cdn.jsdelivr.net'], scriptSrc: [`'self'`, `https: 'unsafe-inline'`, `cdn.jsdelivr.net`], }, }, }); // If you are not going to use CSP at all, you can use this: app.register(helmet, { contentSecurityPolicy: false, }); ```