以下是针对错误 "unable to verify the first certificate" 的中文解决方案:
1. 诊断根本原因
此错误表示 Node.js 无法验证目标服务器的 SSL/TLS 证书。常见原因:
- 自签名证书(开发环境常见)。
- 服务器未提供完整的证书链(缺少中间证书)。
- 客户端环境中的CA证书库过期。
- 公司代理/防火墙 使用不受信任的证书拦截流量。
2. 安全解决方案(推荐)
A. 将证书添加到信任库
如果服务器使用自签名或私有 CA 颁发的证书:
- 方法一:在 HTTPS 请求中指定
ca选项:const https = require('https'); const fs = require('fs'); // 读取证书文件(PEM格式) const cert = fs.readFileSync('./path/to/cert.pem'); const options = { hostname: 'example.com', port: 443, path: '/', method: 'GET', ca: cert, // 指定证书 }; https.request(options, (res) => { /* ... */ }); - 方法二:通过环境变量
NODE_EXTRA_CA_CERTS添加证书:export NODE_EXTRA_CA_CERTS=/path/to/cert.pem node app.js
B. 修复服务器的证书链
确保服务器返回完整的证书链(包括根证书和中间证书)。用以下命令检查:
openssl s_client -connect example.com:443
如果输出中 Certificate chain 只有1个证书,说明证书链不完整。需重新配置服务器。
3. 临时解决方案(仅限开发环境)
A. 禁用证书验证
在 HTTPS 选项中设置 rejectUnauthorized: false(生产环境禁用!):
const agent = new https.Agent({
rejectUnauthorized: false // 关闭证书验证
});
const options = {
hostname: 'example.com',
agent: agent
};
B. 全局禁用 TLS 验证(不推荐)
通过环境变量临时关闭验证:
export NODE_TLS_REJECT_UNAUTHORIZED=0
node app.js
4. 其他检查
- 更新 CA 证书库:
- Linux:
sudo update-ca-certificates - Windows: 更新系统根证书。
- Linux:
- 检查系统时间:证书验证依赖时间,确保客户端时间准确。
- 代理问题:如果使用代理,将代理的 CA 证书添加到信任库。
总结
- 优先修复服务器证书链(最佳实践)。
- 将证书添加到 Node.js 信任库(安全可靠)。
- 仅在开发环境临时使用
rejectUnauthorized: false。
生产环境务必确保证书安全! 🔒