Vite应用在localhost:5173正常运行,127.0.0.1:5173无法访问
Vite.js应用仅localhost可访问,127.0.0.1无法访问的解决方法
问题说明
- 设备:Intel芯片Mac,系统为MacOS Ventura 13.0.1
- Vite.js项目可通过
http://localhost:5173/正常访问,但http://127.0.0.1:5173/无法打开 - 普通React项目同时支持
http://localhost:3000和http://127.0.0.1:3000访问 - 已尝试修改
/etc/hosts添加127.0.0.1 myapp.local,问题未解决
可行解决方案
1. 修改Vite服务器监听配置
Vite默认可能仅绑定localhost,需调整配置让服务器监听所有网络接口:
- 打开项目根目录的
vite.config.js(或vite.config.ts) - 添加
server.host配置项:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { host: '0.0.0.0' // 允许通过所有IP访问开发服务器 } })
- 重启Vite开发服务器,再次尝试访问
http://127.0.0.1:5173/
2. 确认hosts文件的本地映射有效性
从你提供的hosts截图来看,127.0.0.1 localhost的默认映射是正常的,可再通过以下步骤验证:
- 打开终端执行
ping localhost,确认返回的IP是127.0.0.1 - 执行
ping 127.0.0.1,检查是否能正常连通 - 若hosts文件存在异常,恢复默认的两行映射:
127.0.0.1 localhost ::1 localhost
3. 排除防火墙或代理工具干扰
- 临时关闭Mac自带防火墙(路径:系统设置 > 网络 > 防火墙),测试是否能访问
- 如果你正在使用代理工具(如Charles、Clash等),暂时关闭代理服务,排除拦截可能
4. 清除本地DNS缓存
Mac Ventura系统下执行以下命令刷新DNS缓存:
sudo dscacheutil -flushcache sudo killall -HUP mDNSResponder
完成后重启浏览器和Vite服务器,再次测试访问
内容的提问来源于stack exchange,提问作者noobCoder19
相关产品推荐
相关产品推荐

