在 Nestjs 中使用 https 和 Axios 请求

时间:2021-07-03 21:03:42

标签: javascript typescript https axios nestjs

我目前有一个 Nestjs 服务器设置,当端点之一被 GET 请求命中时,我正在尝试执行 Axios 请求。这是 controller.ts 代码:

@Controller()
export class TestController {
    constructor(private readonly testService: TestService) {}

    @Get('testData')
    testData() {
        return this.testService.testData();
    }
}

Service.ts:

@Injectable()
export class TestService {
    status(): string {
        return 'OK'
    }

    testData(): Promise<any> {
        return helper.getTestData();
    }
}

其中 helper.getTestData() 只是对具有以下功能的帮助文件的调用:

export async function getTestData(): Promise<any> {
    const result = await axios({
        url: tempURL,
        method: 'GET',
        timeout: 3000,
        httpsAgent: new https.Agent({
            rejectUnauthorized: false,
        }),
    });

我能够访问此端点 tempURL,但遇到以下错误消息:Cannot read property 'Agent' of undefined。我知道我尝试访问的端点需要证书,这就是我必须在 Axios 请求中包含 httpsAgent 参数的原因。如果我不包括 httpsAgent 参数,我会收到以下消息 Error: unable to verify the first certificate in nodejs

有没有办法配置 Nestjs 以使用 https?或者有没有其他方法可以在 Nestjs 内部处理这个授权问题?使用 Postman 一切正常,所以我假设这是一个 Nestjs 问题。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您应该使用命名空间导入而不是 import https from 'https';import * as https from 'https'; 或在您的 tsconfig 文件中将 esModuleInterop 设置为 true(在 { {1}})