0

我正在使用Nestjs (7.x) 和Fastify (with @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();
4

2 回答 2

4

在为 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();

另一种选择是将类型传递给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();

两种方式都有效,尽管只有第二种方式是类型安全的。

于 2020-05-16T22:22:25.377 回答
1
import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { fastifyHelmet } from 'fastify-helmet';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  app.register(fastifyHelmet)
  await app.listen(3000);
}
bootstrap();

试试这个。从包中导入 fastifyHelmet,用它来注册。

于 2021-04-16T15:13:34.437 回答