NestJS 中间件未执行

Rom*_*sov 1 javascript node.js typescript nestjs fastify

从模块连接时,NestJS 类或功能中间件不会运行。它也不适用于单个路径、控制器或每个路径。从 main.ts 连接功能中间件工作正常。

//main.ts
import { ValidationPipe } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'
import { AppModule } from './app.module'

declare const module: any

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter())

  app.useGlobalPipes(new ValidationPipe())

  await app.listen(2100)

  if (module.hot) {
    module.hot.accept()
    module.hot.dispose(() => app.close())
  }
}
bootstrap()
Run Code Online (Sandbox Code Playgroud)
//app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'
import { AuthMiddleware } from './middleware/auth.middleware'
import { UserModule } from './user/user.module'

@Module({
  imports: [UserModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes('(.*)')
  }
}
Run Code Online (Sandbox Code Playgroud)
//auth.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common'
import { FastifyRequest, FastifyReply } from 'fastify'

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  use(req: FastifyRequest, res: FastifyReply, next: () => void) {
    console.log('test auth middleware')
    next()
  }
}
Run Code Online (Sandbox Code Playgroud)

预期输出:测试认证中间件
实际:无

Rom*_*sov 6

问题是安装“fastify”包和“@nestjs/platform-fastify”。另外,如果你删除了“fastify”包,那么“@nestjs/platform-fastify”包中​​使用的依赖也会被删除,因此无法正常工作。如果您已经安装了这两个软件包,请卸载“fastify”并重新安装“@nestjs/platform-fastify”。