【问题标题】:NestJS Middleware Not ExecutedNestJS 中间件未执行
【发布时间】:2021-01-06 17:12:11
【问题描述】:

从模块连接时,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()
  }
}

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

【问题讨论】:

    标签: javascript node.js typescript nestjs fastify


    【解决方案1】:

    问题在于安装“fastify”包和“@nestjs/platform-fastify”。另外,如果你删除了“fastify”包,那么“@nestjs/platform-fastify”包中​​使用的依赖也会被删除,所以它不会正常工作。如果你已经安装了这两个包,卸载“fastify”并重新安装“@nestjs/platform-fastify”。

    【讨论】:

    • 我同意,遇到了同样的问题,然后就可以了。
    • 我发现确保您安装与 @nestjs/platform-fastify 使用的相同的 fastify 版本也可以解决问题。
    • 你是对的,它对我有同样的解决方案,谢谢你
    【解决方案2】:

    我没有使用 Fastify,但我的中间件没有执行,甚至直接取自文档。我构建了我的项目 (npm run build),然后回到开发模式 npm run start:dev,这似乎可行。如有疑问,请调查 /dist 目录。

    【讨论】:

      猜你喜欢
      • 2021-08-08
      • 2019-08-15
      • 1970-01-01
      • 2022-12-21
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      相关资源
      最近更新 更多