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

如何在Node.js内置fetch()中选择性允许自签名证书?

Node.js内置fetch允许特定请求使用自签名证书

当使用node-fetch或Node.js原生https模块时,我们可以通过自定义https.Agent并设置rejectUnauthorized: false来跳过HTTPS证书验证,代码示例如下:

const fetch = require('node-fetch');
const https = require('https');

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

const response = await fetch(url, {
  method: 'POST',
  headers: headers,
  body: body,
  agent: httpsAgent,
});

但Node.js内置的fetch基于undici实现,并非直接使用Node.js原生的http/https模块,因此直接传入https.Agent会无效,报错DEPTH_ZERO_SELF_SIGNED_CERT。如果不想全局禁用HTTPS验证,仅针对特定测试端点允许自签名证书,可以通过以下方法解决:

解决方案:使用undici的Dispatcher

内置fetch接受dispatcher参数,我们可以创建undici的Agent实例并配置证书验证选项,传入该参数即可:

const { Agent } = require('undici');

// 创建undici Agent,禁用当前Agent的证书验证
const undiciAgent = new Agent({
  connect: {
    rejectUnauthorized: false
  }
});

// 发起请求时传入dispatcher
const response = await fetch('https://my_test_api.local/test', {
  method: 'GET',
  dispatcher: undiciAgent
});

补充说明

  • 内置fetch的底层实现是undici,因此需要遵循undici的API规范,而非node-fetch的参数约定;
  • 这种方式仅会影响使用该dispatcher的请求,不会全局修改HTTPS验证规则,符合仅针对特定端点测试的需求;
  • 如果不需要复用Agent,也可以直接在dispatcher中传入配置对象:
const response = await fetch('https://my_test_api.local/test', {
  method: 'GET',
  dispatcher: new Agent({
    connect: {
      rejectUnauthorized: false
    }
  })
});

内容的提问来源于stack exchange,提问作者Tomáš Zato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:07:40