Nuxt 项目安装时报错(TypeError: fetch failed)的解决
在安装 Nuxt 项目时报错:ERROR Error: Failed to download template from registry,解决方式是在本地的 hosts 文件中加一行配置:185.199.109.133 raw.githubusercontent.com
在安装 Nuxt 项目时报错:ERROR Error: Failed to download template from registry: Failed to download https://raw.githubusercontent.com/nuxt/starter/templates/templates/v3.json: TypeError: fetch failed.

报错原因
可能是因为国内的网络政策,对 raw.githubusercontent.com
进行了 DNS 污染,这会导致你的请求在到达 DNS 服务器后解析到错误的服务器 IP 地址,从而无法正确连接到 githubusercontent 的服务,所以当 ping 这个地址的时候也是 ping 不通的(ping raw.githubusercontent.com
)。

解决办法:在本地配 Host
在本地的 hosts 文件中新加一行配置,即可解决报错问题:
185.199.109.133 raw.githubusercontent.com
上面的配置可以模拟 DNS,这里的 IP 地址你可以在https://ipleak.net/?q=raw.githubusercontent.com%2F
查到,不过通常都是185.199.109.133
,如果配了之后不行,可以换一个 ip 试试,比如换成185.199.110.133
或其它可用 ip,当然更稳妥的方法就是把所有的 ip 都配上去,形如:
185.199.108.133 raw.githubusercontent.com
185.199.109.133 raw.githubusercontent.com
185.199.110.133 raw.githubusercontent.com
185.199.111.133 raw.githubusercontent.com

关于配置方法,见下文。
Windows
下面是在 Windows 中编辑 Hosts 文件的步骤:
1.打开 Notepad 作为管理员:
在开始菜单中搜索 "Notepad",右键点击 "Notepad" 并选择 "以管理员身份运行"。

2.打开 Hosts 文件:
在 Notepad 中,点击 "文件" 菜单,然后选择 "打开"。导航到以下路径:C:\Windows\System32\drivers\etc\
, 然后打开"hosts"文件。

3.编辑 Hosts 文件:
在文件的末尾添加新的行,每行的格式是 IP 地址,空格,域名,将下面的配置添加进去即可。
185.199.109.133 raw.githubusercontent.com
这会将 raw.githubusercontent.com
映射到主机(185.199.109.133
)。
4.保存文件:
在 Notepad(记事本) 中编辑完 Hosts 文件后,保存即可。
5.创建 Nuxt 项目:
Hosts 配置后,我们可以再 ping 一下(ping raw.githubusercontent.com
),发现成功了:

Nuxt 项目也创建成功( npx nuxi@latest init next-demo
),不成功的话重启 vscode 编辑器试试,或者给那个 DNS 地址换一个 ip
,比如换成185.199.110.133
或其它可用 ip,当然更稳妥的方法就是把所有的 ip 都配上去,形如:
185.199.108.133 raw.githubusercontent.com
185.199.109.133 raw.githubusercontent.com
185.199.110.133 raw.githubusercontent.com
185.199.111.133 raw.githubusercontent.com

macOS
macOS 的 Hosts 文件地址是/etc/hosts
,也是在文件后面新增一行:
185.199.109.133 raw.githubusercontent.com
你可以通过以下步骤来编辑 Hosts 文件:
- 打开终端(Terminal),可以按 F4 来搜索“终端”这个词来打开。
- 输入以下命令以使用超级用户权限编辑 Hosts 文件:
sudo nano /etc/hosts
- 提示输入密码时,输入你的管理员密码(开机密码)。
- 使用 nano 编辑器进行编辑。编辑完成后,按
Control + O
保存文件,然后按Control + X
退出编辑器。 - 要使更改生效,可以刷新 DNS 缓存:
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
这样,你的 Hosts 文件修改就会生效。如果 Nuxt 项目还是安装不成功的话重启 vscode 编辑器试试,或者给那个 DNS 地址换一个 ip
,比如换成185.199.110.133
或其它可用 ip,当然更稳妥的方法就是把所有的 ip 都配上去,形如:
185.199.108.133 raw.githubusercontent.com
185.199.109.133 raw.githubusercontent.com
185.199.110.133 raw.githubusercontent.com
185.199.111.133 raw.githubusercontent.com

注意事项
编辑 Hosts 文件需要管理员权限,如果你没有管理员权限,你可能无法保存对 Hosts 文件的更改。

了解更多: