如何在 Nest.js 中间件中使用服务

How to consume a Service in Nest.js middleware

我需要在某些中间件中使用 @nestjs/axios 中的 HttpService 来验证验证码响应。

我已经在 app.module.ts 中注册了这样的中间件:

@Module({
  // ...
  controllers: [AppController],
  providers: [AppService, HttpService] <---- added HttpService here
})

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(CaptchaMiddleware)
      .forRoutes(
        { path: '/users', method: RequestMethod.POST }
      );
  }
}

这就是 captcha.middleware.ts 的样子:

@Injectable()
export class CaptchaMiddleware implements NestMiddleware {

    constructor(
        private readonly httpService: HttpService
    ) { }

    async use(req: Request, res: Response, next: NextFunction) {

        // ... code to verify captcha ...
      
    }
}

但是我得到这个错误:

 ERROR [ExceptionHandler] Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument AXIOS_INSTANCE_TOKEN at index [0] is available in the AppModule context.

Potential solutions:
- If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current AppModule?
- If AXIOS_INSTANCE_TOKEN is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]
  })

HttpService 添加为 CaptchaMiddleware 的依赖项的正确方法是什么?

您应该导入 HttpModule,而不是提供 HttpServiceJust like it's described in the docs。当您提供一个提供者时,Nest 会尝试创建该提供者的实例,当您导入模块时,Nest 将重新使用该提供者(如果它存在)或使用模块的提供者定义创建一个新的提供者。