在 Nestjs 中使用 https 和 Axios 请求
Using https with Axios request in 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 问题。感谢任何帮助。
而不是 import https from 'https';
你应该使用 namespace import: import * as https from 'https';
或将 esModuleInterop
设置为 true
tsconfig 文件(在 compilerOptions
下)
我目前有一个 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 问题。感谢任何帮助。
而不是 import https from 'https';
你应该使用 namespace import: import * as https from 'https';
或将 esModuleInterop
设置为 true
tsconfig 文件(在 compilerOptions
下)