Node.js本地运行报错:unable to get local issuer certificate求助
解决Node.js "unable to get local issuer certificate" 错误
问题重现
运行Node.js代码时触发以下错误:
(node:7532) UnhandledPromiseRejectionWarning: Error: unable to get local issuer certificate at TLSSocket.onConnectSecure (_tls_wrap.js:1048:34) at TLSSocket.emit (events.js:182:13) at TLSSocket._finishInit (_tls_wrap.js:628:8) (node:7532) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:7532) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
已尝试以下操作但未生效:
npm set strict-ssl=falsenpm config set strict-ssl falseexport NODE_TLS_REJECT_UNAUTHORIZED=0
有效解决方案
1. 导入本地根证书到Node.js信任列表
如果处于企业代理或自定义证书环境,需将本地根证书配置到Node.js:
- 找到本地根证书文件(通常为
.pem/.crt格式) - 设置环境变量指向证书路径:
# Windows 命令提示符 set NODE_EXTRA_CA_CERTS=C:\path\to\your\root-cert.crt # Windows PowerShell $env:NODE_EXTRA_CA_CERTS = "C:\path\to\your\root-cert.crt" # macOS/Linux export NODE_EXTRA_CA_CERTS=/path/to/your/root-cert.crt - 重启Node.js进程后重新运行代码
2. 修复未处理的Promise拒绝
错误附带的Promise未捕获警告必须通过代码处理:
- 使用
async/await时用try/catch包裹逻辑:async function requestData() { try { // 你的HTTPS请求代码 const res = await fetch('https://your-target-url.com'); const data = await res.json(); console.log(data); } catch (err) { console.error('请求失败:', err); } } - 使用
.then/.catch链式调用时必须添加.catch():fetch('https://your-target-url.com') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error('请求失败:', err));
3. 确保npm配置全局生效
如果之前的npm配置未生效,添加全局标记持久化设置:
npm config set strict-ssl false -g
⚠️ 注意:此方法会降低安全性,仅在测试或可信环境下使用。
内容的提问来源于stack exchange,提问作者Rohith kumar
相关产品推荐
相关产品推荐

