Nestjs - 无法向中间件注入服务

Nest JS - Unable to inject service to middlewere

我创建了一个 auth middlewere 来检查每个请求,middlewere 正在使用服务器(仅当在 req.connection 中找不到数据时)。 我正在尝试将服务注入我的中间件,但我不断收到相同的错误“Nest 无法解析 AuthenticationMiddleware 的依赖项 (?)。请验证 [0] 参数在当前上下文中是否可用。”

身份验证模块:

@Module({
   imports: [ServerModule],
   controllers: [AuthenticationMiddleware],
})
export class AuthenticationModule {
}

身份验证中间件:

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {

constructor(private readonly service : UserService) {}

resolve(): (req, res, next) => void {
 return (req, res, next) => {
   if (req.connection.user)
    next();

  this.service.getUsersPermissions()     
  }
}

服务器模块:

@Module({
 components: [ServerService],
 controllers: [ServerController],
 exports: [ServerService]
})    
 export class ServerModule {}

应用程序模块:

@Module({
  imports: [
    CompanyModule,
    ServerModule,
    AuthenticationModule
  ]
})

export class ApplicationModule implements NestModule{
  configure(consumer: MiddlewaresConsumer): void {
  consumer.apply(AuthenticationMiddleware).forRoutes(
      { path: '/**', method: RequestMethod.ALL }
   );
 }
}

您的应用程序无法解析 AuthMiddleware 依赖项,可能是因为您向其中注入了 UserService,但是您导入 AuthenticationModuleServerModule 只是导出了 ServerService。所以,应该做的是:

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {

  constructor(private readonly service : ServerService) {}

  resolve(): (req, res, next) => void {
    return (req, res, next) => {
      if (req.connection.user)
        next();

    this.service.getUsersPermissions()     
  }
}

您可以找到有关 NestJS 依赖容器的更多信息 here