You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nest JS中如何配置Axios跳过SSL证书校验接受连接

NestJS 中配置 Axios 跳过 SSL 证书校验方法

NestJS 中的 Axios 能力由官方 @nestjs/axios 包封装的 HttpModule 提供,原生 Node 层的 HTTPS Agent 配置可以直接透传,不需要额外适配,具体实现分两种场景:

全局统一配置(所有 HttpService 发起的请求默认生效)

在模块层导入 HttpModule 时传入自定义 HTTPS 代理配置即可,示例:

import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import * as https from 'https';

@Module({
  imports: [
    HttpModule.register({
      timeout: 5000,
      maxRedirects: 5,
      // 核心:配置关闭证书校验的HTTPS代理
      httpsAgent: new https.Agent({
        rejectUnauthorized: false,
      }),
    }),
  ],
})
export class AppModule {}

如果需要结合环境配置动态加载参数,使用 registerAsync 方式注册:

import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import * as https from 'https';

@Module({
  imports: [
    HttpModule.registerAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        timeout: configService.get('HTTP_TIMEOUT'),
        httpsAgent: new https.Agent({
          // 仅非生产环境关闭证书校验
          rejectUnauthorized: configService.get('NODE_ENV') === 'production',
        }),
      }),
    }),
  ],
})
export class AppModule {}

单次请求单独配置

如果只需要针对个别接口跳过证书校验,不需要全局修改配置,可以在具体请求时传入agent参数:

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import * as https from 'https';

@Injectable()
export class BusinessService {
  constructor(private readonly httpService: HttpService) {}

  postToRemoteService() {
    return this.httpService.post(
      'https://目标线上服务地址',
      // 请求体参数
      { data: 'xxx' },
      // 请求配置
      {
        httpsAgent: new https.Agent({
          rejectUnauthorized: false,
        }),
      }
    );
  }
}

关键注意点

  • rejectUnauthorized: false 绝对不能在生产环境使用,该配置会关闭SSL证书合法性校验,存在中间人攻击的严重安全风险,仅可用于本地开发、测试联调场景
  • 建议所有环境相关的校验逻辑都通过环境变量控制,避免开发配置被误带到生产
  • 问题对应报错截图:
    Error

内容的提问来源于stack exchange,提问作者hope

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 06:46:04