首页 > 解决方案 > 如何在 Nest.js 中间件中使用服务

问题描述

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

我已经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什么?

标签: nestjs

解决方案


您应该导入HttpModule,而不是提供HttpService. 就像它在文档中描述的一样。当您提供提供者时,Nest 会尝试创建该提供者的实例,当您导入模块时,Nest 将重新使用提供者(如果存在)或使用模块的提供者定义创建一个新的提供者。


推荐阅读