如何使用Fastify在Nestjs项目上配置头盔?

时间:2020-05-16 21:06:25

标签: nestjs fastify helmet.js

我正在使用 Nestjs (7.x)和 Fastify (与@nestjs/platform-fastify一起使用)。 我正在尝试在项目(fastify-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();

2 个答案:

答案 0 :(得分:1)

在注册中间件以进行固定时,您有两个选择。第一种是获取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();

这两种方法都是有效的,尽管只有第二个选项是安全类型。

答案 1 :(得分:0)

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,使用它进行注册。