Node.js 18中fetch设置rejectUnauthorized:false无效问题求助
Node.js 18中Fetch忽略自签名证书错误的解决方法
你在测试服务器TLS配置时,使用自签名证书,尝试通过https.Agent设置rejectUnauthorized: false来忽略证书错误,但在Node.js 18的Fetch API中无法生效,报错SELF_SIGNED_CERT_IN_CHAIN。你的代码如下:
const https = require('https'); const httpsAgent = new https.Agent({ rejectUnauthorized: false, }); const url = 'https://myoauthendpoint/oauthProtected'; const options = { agent: httpsAgent, method: 'GET', }; const start = async () => { console.log('starting fetch'); try { const response = await fetch(url, options); if (response.ok) { const data = await response.json(); console.log({ data }); } console.log({ response }); } catch (err) { console.log({ err }); } }; start();
运行后出现的错误:
{ err: TypeError: fetch failed at Object.fetch (node:internal/deps/undici/undici:11413:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async start (/Users/danielchicchon/Projects/testing/misc/fetch/start.js:19:22) { cause: Error: self-signed certificate in certificate chain at TLSSocket.onConnectSecure (node:_tls_wrap:1540:34) at TLSSocket.emit (node:events:513:28) at TLSSocket._finishInit (node:_tls_wrap:959:8) at ssl.onhandshakedone (node:_tls_wrap:743:12) { code: 'SELF_SIGNED_CERT_IN_CHAIN' } } }
解决方法
1. 使用Undici的Agent(推荐)
Node.js 18及以上的Fetch API基于Undici实现,原生https.Agent不兼容,需要使用Undici提供的Agent:
首先安装Undici:
npm install undici
修改代码:
const { Agent } = require('undici'); const undiciAgent = new Agent({ connect: { rejectUnauthorized: false } }); const url = 'https://myoauthendpoint/oauthProtected'; const options = { dispatcher: undiciAgent, // 注意此处用dispatcher而非agent method: 'GET', }; const start = async () => { console.log('starting fetch'); try { const response = await fetch(url, options); if (response.ok) { const data = await response.json(); console.log({ data }); } console.log({ response }); } catch (err) { console.log({ err }); } }; start();
2. 设置环境变量临时禁用证书验证
在启动脚本时添加环境变量,全局禁用当前Node进程的证书验证:
NODE_TLS_REJECT_UNAUTHORIZED=0 node your-script.js
注意:仅适合开发测试场景,生产环境绝对禁止使用
3. 更安全的方式:指定自签名证书为可信CA
如果不想完全禁用验证,可以将自签名证书添加到可信列表,既通过验证又保留安全性:
const { Agent } = require('undici'); const fs = require('fs'); const undiciAgent = new Agent({ connect: { ca: fs.readFileSync('/path/to/your-self-signed-cert.pem') } }); // 后续fetch配置同方法1
内容的提问来源于stack exchange,提问作者pythonNovice
相关产品推荐
相关产品推荐

