Andrew
Andrew

Reputation: 501

Using https with Axios request in Nestjs

I currently have a Nestjs server setup and am attempting to perform an Axios request when one of the endpoints is hit with a GET request. Here is the controller.ts code:

@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();
    }
}

Where helper.getTestData() is just a call to a helper file with the following function:

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

I am able to hit this endpoint tempURL but encounter the following error message: Cannot read property 'Agent' of undefined. I know that the endpoint I am attempting to hit requires a cert, which is why I must include the httpsAgent argument inside the Axios request. If I don't include the httpsAgent argument, I receive the following message Error: unable to verify the first certificate in nodejs.

Is there a way to configure Nestjs to work with https? Or is there another way to handle this authorization issue inside of Nestjs? Using Postman everything works fine so I'm assuming it is a Nestjs issue. Any help is appreciated.

Upvotes: 3

Views: 6254

Answers (1)

Micael Levi
Micael Levi

Reputation: 6665

instead of import https from 'https'; you should use the namespace import: import * as https from 'https'; or set the esModuleInterop to true in your tsconfig file (under compilerOptions)

Upvotes: 6

Related Questions