Eti*_*nne 1 helmet.js nestjs fastify nestjs-fastify
我正在使用Nestjs (7.x) 和Fastify(带有@nestjs/platform-fastify)。我正在尝试在我的项目 ( ) 中安装Helmetfastify-helmet,但我无法弄清楚如何将其与 Nestjs 集成/配置。将其带上飞机的正确方法是什么?
这是我的 Nestjs 引导程序:
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { MainModule } from './main.module';
import * as helmet from 'fastify-helmet';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(MainModule);
await app.listen(3000, 0.0.0.0);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
在为 fastify 注册中间件时,您有两种选择。第一个是获取 HttpAdapter 的实例并使用register其中的方法。这可以像这样完成:
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import * as helmet from 'fastify-helmet';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
app
.getHttpAdapter()
.getInstance()
.register(helmet);
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
另一种选择是将类型传递给NestFactory.create方法,然后使用app.register. 这只蜜蜂可以在这里看到
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import * as helmet from 'fastify-helmet';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
app.register(helmet);
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
两种方法都是有效的,但只有第二种方法是类型安全的。
| 归档时间: |
|
| 查看次数: |
4818 次 |
| 最近记录: |