无法使用npm/Yarn创建React应用:超时与加密错误求助
一、问题现象
- 创建React应用时,npm/yarn均返回网络超时错误:
npm ERR! code ETIMEDOUT
npm ERR! syscall connect
npm ERR! errno ETIMEDOUT
npm ERR! network request to http://registry.npmjs.org/creat-react-app failed, reason: connect ETIMEDOUT 2606:4700::6810:1223:80
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly. See: 'npm help config'npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\fluva\AppData\Local\npm-cache_logs\2023-04-28T03_27_08_973Z-debug-0.log
- 可正常执行
npm init -y,但打开已有React应用时出现SSL相关错误:
Error: error:0308010C:digital envelope routines::unsupported
执行$env:NODE_OPTIONS = "--openssl-legacy-provider"后可通过yarn start启动应用,但无法安装新依赖,安装过程卡在:
| idealTree:tryagain: sill idealTree buildDeps
二、已完成的排查操作
- 确认无代理、防火墙干扰(已禁用所有安全软件测试,结果一致)
- 卸载并重装Node.js、OpenSSL 1.1.1
三、环境信息
- node v18.16.0
- npm 9.6.0
- openssl version OpenSSL 1.1.1t 7 Feb 2023
- yarn -v 1.22.19
- 操作系统:Windows 10
- 问题同时出现在台式机和笔记本电脑上,推测为网络相关问题
四、解决办法
1. 切换npm/yarn镜像源到国内源
默认的npm官方源在国内访问不稳定,切换到国内镜像可改善网络问题:
# 设置npm镜像为淘宝源 npm config set registry https://registry.npmmirror.com/ # 验证镜像是否生效 npm config get registry # 设置yarn镜像为淘宝源 yarn config set registry https://registry.npmmirror.com/
2. 强制Node.js使用IPv4网络
部分网络环境IPv6支持不佳,Node.js默认优先使用IPv6会导致连接超时,可强制使用IPv4:
- 临时生效(当前终端):
set NODE_OPTIONS=--dns-result-order=ipv4first
- 永久生效(系统环境变量):
- 打开Windows「系统属性」→「高级」→「环境变量」
- 在「系统变量」区域点击「新建」,变量名填
NODE_OPTIONS,变量值填--dns-result-order=ipv4first - 重启终端后生效
3. 清除npm/yarn缓存
缓存损坏也可能导致安装卡住,执行以下命令清除缓存:
# 清除npm缓存 npm cache clean --force # 清除yarn缓存 yarn cache clean
4. 修改DNS服务器
将本地DNS改为公共DNS,可解决域名解析问题:
- 谷歌公共DNS:
8.8.8.8、8.8.4.4 - 阿里云公共DNS:
223.5.5.5、223.6.6.6
修改步骤:
- 打开「网络和共享中心」→ 点击当前网络连接 →「属性」→「Internet协议版本4(TCP/IPv4)」→「属性」
- 选择「使用下面的DNS服务器地址」,填入上述DNS地址
- 点击「确定」后重启网络
内容的提问来源于stack exchange,提问作者fluva74

