【问题标题】:Nest JS - Unable to inject service to middlewereNestjs - 无法向中间件注入服务
【发布时间】:2021-05-24 15:27:38
【问题描述】:

我创建了一个身份验证中间件来检查每个请求,中间件正在使用服务器(仅当在 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 }
   );
 }
}

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

    您的应用程序无法解析AuthMiddleware 依赖项,可能是因为您将UserService 注入其中,但您导入到AuthenticationModule 中的ServerModule 只是导出了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 的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 2021-12-29
      • 1970-01-01
      • 2022-09-24
      • 2018-11-16
      • 2020-07-08
      • 2019-02-26
      相关资源
      最近更新 更多