【问题标题】:Using https with Axios request in Nestjs在 Nestjs 中使用 https 和 Axios 请求
【发布时间】:2021-09-15 06:41:52
【问题描述】:

我目前有一个 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 问题。任何帮助表示赞赏。

【问题讨论】:

  • 看起来 httpsundefined 不知何故
  • @MicaelLevi https 已定义,我已将其正确导入文件。还有,https是原生模块,怎么会是undefined呢?
  • 取决于您如何导入它,它可以。堆栈跟踪中出现错误Cannot read property 'Agent' of undefined 的行与httpsAgent: new https.Agent 相同吗?
  • @MicaelLevi 是的,错误在httpsAgent: new https.Agent 行。我目前导入如下:文件顶部import https from 'https';
  • @MicaelLevi 你是对的,问题在于我是如何导入的。 import https from 'https' 无效,但 import { Agent } from 'https' 有效。谢谢!

标签: javascript typescript https axios nestjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2020-09-26
    • 2019-06-11
    相关资源
    最近更新 更多