未执行NestJS中间件

问题描述

从Module连接时,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()
//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('(.*)')
  }
}
//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()
  }
}

预期输出:测试身份验证中间件
实际:没事

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...