Node.js调用OpenAI API遭遇SSL证书错误,求安全解决方案
问题分析与解决方案
可能的原因
- Node.js版本过旧:Node.js 14.17.0已停止维护,其内置的根证书库可能未包含OpenAI API证书的最新颁发机构,导致无法验证证书有效性。
- OpenAI SDK配置错误:若使用的是OpenAI SDK v4及以上版本,自定义HTTPS Agent的配置字段应为
httpsAgent而非agent,之前的代码配置未生效,因此禁用验证的方法无法起作用。 - 网络环境拦截:公司代理、防火墙或杀毒软件的SSL扫描功能可能替换了原始证书,导致Node.js无法识别合法证书。
- Windows证书存储问题:Node.js在Windows环境下可能未正确加载系统信任的根证书。
安全的解决方案
1. 优先更新Node.js版本
Node.js 14已终止维护,升级到LTS版本(如18.x或20.x)会自动更新内置根证书库,这是解决证书问题最彻底且安全的方式。
2. 修正OpenAI SDK的Agent配置(若无法升级Node.js)
如果使用OpenAI SDK v4+,需将自定义Agent配置到httpsAgent字段,而非agent。示例代码:
const OpenAI = require("openai"); const https = require("https"); // 若要安全验证,建议替换为合法的根证书,而非禁用验证 const agent = new https.Agent({ rejectUnauthorized: true, // 保持启用验证 // 可选:添加信任的根证书 // ca: fs.readFileSync("/path/to/root-certificate.pem") }); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, httpsAgent: agent // 注意这里是httpsAgent }); async function getCompletion() { try { const chatCompletion = await openai.chat.completions.create({ messages: [{ role: "user", content: "Say this is a test" }], model: "gpt-3.5-turbo", }); console.log(chatCompletion); } catch (error) { console.error("Error:", error); } } getCompletion();
3. 添加信任的根证书
- 打开浏览器访问
https://api.openai.com,查看证书详情,导出根证书(如DigiCert Global Root CA)为PEM格式文件。 - 通过环境变量指定额外CA证书:
或在代码中加载证书到Agent:# Windows命令行 set NODE_EXTRA_CA_CERTS=C:\path\to\your\root-cert.pemconst fs = require("fs"); const agent = new https.Agent({ ca: fs.readFileSync("/path/to/root-cert.pem"), rejectUnauthorized: true });
4. 排查网络环境
- 关闭杀毒软件的SSL扫描功能,或添加OpenAI API域名到信任列表。
- 若使用代理,确保代理服务器的证书已添加到系统信任根证书,或在Node.js Agent中配置代理的CA证书。
内容的提问来源于stack exchange,提问作者Michael Ohana
相关产品推荐
相关产品推荐

