Windows 下 npm create astro 报"无法连接网络"的排查
现象
在 Windows 上执行 npm create astro@latest 创建项目,直接报错:
▲ error Unable to connect to the internet.
但同一个终端里网络明明是通的:
curl https://registry.npmjs.org/astro返回 200;npm install下载依赖正常;- 系统代理(
HTTP_PROXY/HTTPS_PROXY环境变量)都已配置。
排查
用一条最小命令复现,验证 Node 原生 fetch 是否走代理:
node -e "fetch('https://registry.npmjs.org/astro').then(r=>console.log(r.status)).catch(e=>console.error(e.message))"
结果超时失败 —— 说明问题不在网络,而在 Node 原生 fetch(undici)默认不读取 HTTP_PROXY / HTTPS_PROXY 环境变量。这一点和 curl、npm 的行为不一样:
| 工具 | 是否自动读代理环境变量 |
|---|---|
| curl | ✅ 会 |
| npm | ✅ 会 |
| wrangler | ✅ 会(会打印 “Proxy environment variables detected”) |
| Node 原生 fetch(create-astro 等 CLI 内部用的) | ❌ 默认不会 |
解决
Node 22 提供了实验性开关 NODE_USE_ENV_PROXY=1,打开后原生 fetch 就会走环境变量里的代理:
# Git Bash
NODE_USE_ENV_PROXY=1 npm create astro@latest
# CMD
set NODE_USE_ENV_PROXY=1 && npm create astro@latest
# PowerShell
$env:NODE_USE_ENV_PROXY='1'; npm create astro@latest
再跑上面的最小复现命令,返回 200,创建项目也正常了。
备注
- 这个坑影响所有内部用 Node 原生
fetch联网的 CLI 工具,报错样式各异,但共同特征是「curl 通、它不通」; - 本机已把
NODE_USE_ENV_PROXY=1写进博客项目的.env,双击发布脚本时会自动带上。