NestJS配置HTTPS Agent时出现https.Agent undefined报错如何解决
NestJS服务初始化HTTPS Agent时报错
Cannot read property 'Agent' of undefined 排查解决 问题场景
基于NestJS框架搭建简单应用,需要调用内部HTTP服务拉取并记录相关业务信息,编写的CallService核心代码如下:
import { HttpService, Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { UserInformation } from 'src/models/userInformation'; import https from 'https'; @Injectable() export class CallService { private authRequest: any; private httpsAgent: https.Agent; constructor( private configService: ConfigService, private httpService: HttpService, ) { this.httpsAgent = new https.Agent({ rejectUnauthorized: false, }); this.authRequest = { username: configService.get('username'), password: configService.get('password'), }; } getUserInformation(): Promise<UserInformation> { var url = this.configService.get('apiEndpoint') + 'scrapt/getUserInfo'; return this.httpService .get(url, { auth: this.authRequest, httpsAgent: this.httpsAgent, }) .toPromise() .then((response) => { return new UserInformation(response.data); }); } }
报错表现
触发getUserInformation方法执行时,控制台抛出错误:Cannot read property 'Agent' of undefined,错误堆栈直接定位到构造函数中创建https.Agent实例的代码行。公开渠道检索未找到直接匹配的解决方案。
问题根因
该报错是Node内置https模块的导入语法和TypeScript编译配置不匹配导致的。在当前代码的编译环境下,使用默认导入语法import https from 'https'获取到的并不是完整的https模块对象,导致访问模块内部的Agent静态属性时,会触发“读取未定义对象属性”的错误。
解决方法
- 替换https模块的导入语法,将原有的默认导入
import https from 'https'修改为命名空间全量导入,确保加载完整的Node内置https模块对象:
这种写法对不同的TypeScript编译配置都兼容,不需要额外调整import * as https from 'https';tsconfig.json的esModuleInterop等编译开关,就能正确访问https模块下的所有静态属性与方法。 - 其余业务逻辑、Agent初始化配置、HTTP请求参数都不需要调整,导入修正后
new https.Agent({ rejectUnauthorized: false })即可正常实例化,实现跳过接口证书校验的预期效果。 - 兼容说明:NestJS内置的
HttpService底层基于Axios实现,将自定义httpsAgent作为请求配置传入是框架原生支持的能力,不需要修改原有接口调用逻辑。
内容的提问来源于stack exchange,提问作者C.Fasolin
相关产品推荐
相关产品推荐

