NestJS中间件未执行

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

期望输出:测试身份验证中间件
实际输出:什么也没有

5个回答

13
安装“fastify”和“@nestjs/platform-fastify”包时出现问题。此外,如果删除“fastify”包,则“@nestjs/platform-fastify”包中使用的依赖项也将被删除,因此它将无法正常工作。如果您已安装了这两个包,请卸载“fastify”并重新安装“@nestjs/platform-fastify”。

我同意,我也遇到了同样的问题,然后问题就解决了。 - user949884
我发现确保安装与@nestjs/platform-fastify使用的相同的fastify版本也可以解决这个问题。 - Sanya Tobi
你说得对,同样的解决方案对我也起作用了,谢谢你。 - Chetan Khandla
我不确定我的package.json应该长什么样子?只需要@nestjs/platform-fastify吗? - Ballon Ura
1
如果您已经安装了@nestjs/platform-fastify和fastify两个包,请使用“npm uninstall”卸载它们,然后只安装@nestjs/platform-fastify。 - Roman Sivtsov

2
我的解决方法是: 我之前定义了一个路由,结尾加上了/
@Controller('v1/partnerPortal/')
export class SubscriptionController {
  constructor()
}

我去掉了斜杠,现在它对我起作用了。

@Controller('v1/partnerPortal')
export class SubscriptionController {
  constructor()
}

我的模块代码:

export class SubscriptionModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(KeyAuthMiddlewareService).forRoutes(SubscriptionController);
  }
}

希望这能有所帮助


谢谢!在路径的末尾添加一个斜线/可以解决问题。 - FooBar

0
在我的情况下,我想要全局应用一个中间件,并在特定模块级别应用另一个中间件。 但由于某些原因,当您在特定模块级别应用中间件时,它不起作用。
export class PartnerModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(ModuleSpecificMiddleware);
  }
}

所以我找到了另一种方法来实现它。在应用程序模块中,您可以像这样分配它。

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware);
    consumer.apply(ModuleSpecificMiddleware).forRoutes(PartnerController); // This was the solution
  }
}

0

我有同样的问题。使用明确的控制器时可以正常工作,但是使用 '*' 就不行。 还尝试过:

forRoutes({path: '*', method: RequestMethod.ALL })

但这似乎也不起作用。 我的解决方案很遗憾,是使用了一个全局的函数中间件,就像这个例子here所示。 这不太可维护,因为它是在main.ts中定义的,而不是在app.module中定义的。 这导致一些e2e测试上的问题,但最终我能够让它工作。只需确保在main.ts中使用中间件,并在创建e2e测试的测试模块时使用中间件即可。

main.ts:

const app = await NestFactory.create(AppModule);
app.use(functionalMiddleware);

在你的端到端测试模块中:

const createAppE2e = async (): Promise<INestApplication> => {
   const moduleRef = await Test.createTestingModule({
     imports: [AppModule],
   });
   const app = moduleRef.createNestApplication();
   app.use(functionalMiddleware);
   await app.init();
   return app;
}

0

我没有使用Fastify,但是即使直接从文档中复制我的中间件也没有执行。我先构建了我的项目(npm run build),然后回到开发模式npm run start:dev,这样似乎就可以工作了。如果有疑问,请调查一下/dist目录。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接