如何在本地用手机测试包含多服务的网站?
解决方案:局域网手机测试本地Web应用的服务地址适配问题
方案1:自动适配当前主机IP(最省心的代码修改)
直接修改全局变量的判断逻辑,不再硬写localhost,而是取当前页面的主机地址,不管是localhost还是局域网IP,自动拼接服务端口。
修改后的代码
// 替换成你的Github Pages域名(比如xxx.github.io) const isProduction = window.location.hostname === 'your-github-pages-domain.github.io'; // 取当前页面的主机地址(localhost或192.168.x.x) const currentHost = window.location.hostname; const globals = { uri: { api: isProduction ? 'https://real/server1/' : `http://${currentHost}:3010/v3`, map: isProduction ? 'https://real/server2/' : `http://${currentHost}:3000` }, // ...其他配置 };
原理
- 生产环境:通过判断Github Pages域名,自动使用真实服务地址,完全不影响现有部署流程。
- 本地测试:不管你在Mac上用
localhost:8080访问,还是手机用192.168.x.x:8080访问,都会自动用当前的主机地址拼接服务端口,彻底避免硬写IP的麻烦。
方案2:用http-server代理转发(无IP依赖)
利用http-server的代理功能,把前端请求的相对路径转发到本地服务,前端代码不用写任何IP或localhost。
步骤1:创建代理配置文件
在项目根目录新建proxy.config.json:
{ "/api": { "target": "http://localhost:3010/v3", "changeOrigin": true, "pathRewrite": {"^/api": ""} }, "/map": { "target": "http://localhost:3000", "changeOrigin": true } }
步骤2:修改前端全局变量
const isProduction = window.location.hostname === 'your-github-pages-domain.github.io'; const globals = { uri: { api: isProduction ? 'https://real/server1/' : '/api', map: isProduction ? 'https://real/server2/' : '/map' }, // ...其他配置 };
步骤3:启动带代理的http-server
npx http-server -P http://localhost:8080 --proxy-config proxy.config.json
原理
- 前端请求
/api时,http-server会自动把请求转发到http://localhost:3010/v3;请求/map则转发到http://localhost:3000。 - 手机访问Mac的IP时,所有服务请求都会通过
http-server代理到本地服务,完全不用关心IP变化,也避免了手机识别不了localhost的问题。
方案3:自定义局域网域名(固定访问地址)
给Mac设置一个固定的局域网域名,比如local.dev,手机通过这个域名访问,不用管IP动态变化。
步骤1:修改Mac的hosts文件
打开终端编辑/etc/hosts:
sudo nano /etc/hosts
添加一行:
127.0.0.1 local.dev
保存后退出(Ctrl+O,回车,Ctrl+X)。
步骤2:绑定服务到局域网可访问地址
启动所有服务时,绑定到0.0.0.0(允许局域网设备访问):
- http-server启动命令:
npx http-server -a 0.0.0.0 -p 8080
- 如果是Node.js的API服务,修改启动代码:
app.listen(3010, '0.0.0.0', () => { console.log('API服务启动在0.0.0.0:3010'); });
- 地图服务同理,绑定到
0.0.0.0:3000。
步骤3:配置手机访问
在手机的WiFi设置中,修改DNS为你的Mac局域网IP,或者直接在手机hosts文件中添加(需要越狱或用第三方工具):
你的Mac局域网IP local.dev
步骤4:修改前端全局变量
const isProduction = window.location.hostname === 'your-github-pages-domain.github.io'; const isLocalDev = window.location.hostname === 'localhost' || window.location.hostname === 'local.dev'; const globals = { uri: { api: isProduction ? 'https://real/server1/' : `http://local.dev:3010/v3`, map: isProduction ? 'https://real/server2/' : `http://local.dev:3000` }, // ...其他配置 };
原理
- 手机通过
http://local.dev:8080访问Web应用,所有服务请求都是local.dev域名,手机能通过DNS或hosts映射到Mac的IP,不管Mac的IP怎么变,都不用修改代码。
内容的提问来源于stack exchange,提问作者punkish
相关产品推荐
相关产品推荐

