NestJS项目使用HttpService时出现AXIOS_INSTANCE_TOKEN依赖解析错误
问题:NestJS中使用HttpService时依赖注入失败
错误信息
[Nest] 74973 - 2023年7月20日 下午3:28:01 ERROR [ExceptionHandler] Nest 无法解析 HttpService 的依赖关系(?)。请确保索引[0]处的参数 AXIOS_INSTANCE_TOKEN 在 AppModule 上下文中可用。 可能的解决方案: - AppModule 是有效的 NestJS 模块吗? - 如果 AXIOS_INSTANCE_TOKEN 是一个提供者,它是否属于当前的 AppModule? - 如果 AXIOS_INSTANCE_TOKEN 是从单独的 @Module 导出的,该模块是否已在 AppModule 中导入? @Module({ imports: [ /* 包含 AXIOS_INSTANCE_TOKEN 的模块 */ ] }) 错误:Nest 无法解析 HttpService 的依赖关系(?)。请确保索引[0]处的参数 AXIOS_INSTANCE_TOKEN 在 AppModule 上下文中可用。
项目代码
文件路径:src/app.module.ts
@Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, load: [configuration] }), CamiModule, ExamplesModule, ItemModule, HttpModule ], controllers: [AppController], providers: [ AppService, HttpHandler, HttpService, { provide: APP_INTERCEPTOR, useClass: PerformanceMonitor } ], }) export class AppModule {}
文件路径:src/item/item.module.ts
@Module({ imports: [HttpModule], providers: [ItemService], exports: [ItemService], }) export class ItemModule { }
文件路径:src/item/item.service.ts
import { HttpService } from '@nestjs/axios'; import { Injectable } from '@nestjs/common'; import { AxiosRequestConfig, AxiosResponse, } from 'axios'; import { firstValueFrom } from 'rxjs'; @Injectable() export class ItemService { constructor(private readonly httpService: HttpService) { } // Get 方法 async get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse> { try { const response = await firstValueFrom(this.httpService.get<T>(url, config)); return response; } catch(error) { throw error } } }
问题排查与解决方案
问题出在AppModule的providers数组中手动注册了HttpService和HttpHandler。
HttpService是由@nestjs/axios的HttpModule提供的,它的构造函数依赖AXIOS_INSTANCE_TOKEN,这个token是HttpModule内部注册的提供者。当你手动在providers里添加HttpService时,Nest会尝试直接创建这个类的实例,但无法找到它需要的AXIOS_INSTANCE_TOKEN依赖,因为手动注册的提供者不会关联HttpModule中的配置。
修复步骤:
- 修改
src/app.module.ts,从providers数组中移除HttpHandler和HttpService:
@Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, load: [configuration] }), CamiModule, ExamplesModule, ItemModule, HttpModule ], controllers: [AppController], providers: [ AppService, { provide: APP_INTERCEPTOR, useClass: PerformanceMonitor } ], }) export class AppModule {}
- 确认
ItemModule已经正确导入HttpModule(你的代码中已经做到这一点),这样ItemService就能通过依赖注入获取到HttpService的实例。 - 重启项目,错误即可解决。
内容的提问来源于stack exchange,提问作者Avinash A
相关产品推荐
相关产品推荐

