| 修改日期 | 内容 | |
|---|---|---|
| 1 | 20260102 | 初版 |
上一篇我们完成了电脑上的API测试,今天要实现一个关键需求:让手机也能访问我们的测试工具。在实际开发中,经常需要在不同设备上测试API,手机访问是个硬需求。
一:问题背景:为什么手机访问不成功?
我的电脑上API测试一切正常,但用手机访问时遇到两个典型问题:
网络连接问题:手机浏览器报错"无法连接到服务器"
配置问题:需要手动修改代码中的IP地址
二:解决方案:两步搞定手机访问
第一步:找到正确的IP地址
关键点:手机和电脑必须在同一个局域网,手机访问的是电脑的局域网IP,不是localhost。
# 在Windows上查看电脑的局域网IP ipconfig # 输出示例: # 无线局域网适配器 WLAN: # IPv4 地址 . . . . . . . . . . . . : 192.168.31.181 # (这就是手机需要访问的地址)第二步:修改配置文件
// 修改前(只能在电脑本机访问) serverBaseUrl: "http://localhost:8080", // 修改后(手机和电脑都能访问) serverBaseUrl: "http://192.168.31.181:8080",三:完整的可配置方案
文件1:config.js(配置文件)
// ================ 服务器配置文件 ================ // 修改这里的IP地址,让手机和电脑都能访问 const config = { // 服务器基础URL(核心配置,只需修改这里) // ⭐ 电脑本机测试:用 localhost 或 127.0.0.1 // ⭐ 手机访问测试:用电脑的局域网IP(运行 ipconfig 查看) serverBaseUrl: "http://192.168.31.181:8080", // ← 修改这里的IP // API端点(一般不需要修改) endpoints: { health: "/health", message: "/api/message" }, // 请求配置(一般不需要修改) requestConfig: { timeout: 5000, headers: { "Content-Type": "application/json" } }, // 开发模式 development: true }; // 浏览器不支持ES6模块导出,直接挂载到window window.APP_CONFIG = config; console.log("✅ 当前服务器地址:", config.serverBaseUrl);文件2:index.html(前端测试页面)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>RESTful通信测试</title> <style> body { font-family: Arial, sans-serif; padding: 20px; max-width: 800px; margin: 0 auto; } button { padding: 10px 20px; font-size: 16px; margin: 10px; } .status { margin: 10px 0; padding: 10px; border: 1px solid #ddd; } </style> </head> <body> <h1>🔗 RESTful通信测试</h1> <button id="sendMessageBtn">发送消息给后端</button> <button id="checkHealthBtn">检查后端状态</button> <div class="status"> <div>前端状态: <span id="frontendStatus">等待发送</span></div> <div>后端响应: <span id="backendResponse">暂无</span></div> </div> <script type="module"> // 导入配置文件 import config from './config.js'; // 获取DOM元素 const sendMessageBtn = document.getElementById('sendMessageBtn'); const checkHealthBtn = document.getElementById('checkHealthBtn'); const frontendStatus = document.getElementById('frontendStatus'); const backendResponse = document.getElementById('backendResponse'); // 显示当前配置 console.log('📋 使用服务器配置:', config.serverBaseUrl); // 发送消息给后端 async function sendMessage() { console.log('🟢 前端:准备发送消息...'); frontendStatus.textContent = '发送中...'; // 使用配置中的服务器地址 const url = `${config.serverBaseUrl}/api/message`; const method = 'POST'; const body = JSON.stringify({ message: '前端说:我已发送' }); console.log('🔍 请求详情:', { url: url, method: method, body: body, timestamp: new Date().toISOString() }); try { const response = await fetch(url, { method: method, headers: config.requestConfig.headers, body: body }); console.log('📥 响应状态:', response.status, response.statusText); const data = await response.json(); console.log('✅ 前端:发送成功,收到回复:', data.reply); frontendStatus.textContent = '发送成功'; backendResponse.textContent = data.reply; } catch (error) { console.error('❌ 前端:发送失败', error); frontendStatus.textContent = '发送失败'; backendResponse.textContent = error.message; } } // 检查后端状态 async function checkHealth() { console.log('🔍 前端:检查后端状态...'); frontendStatus.textContent = '检查中...'; // 使用配置中的服务器地址 const url = `${config.serverBaseUrl}/health`; const method = 'GET'; const body = null; console.log('🔍 请求详情:', { url: url, method: method, body: body, timestamp: new Date().toISOString() }); try { const response = await fetch(url, { method: method, headers: config.requestConfig.headers }); console.log('📥 响应状态:', response.status, response.statusText); const data = await response.json(); console.log('✅ 前端:后端状态正常'); frontendStatus.textContent = '检查完成'; backendResponse.textContent = '后端状态: ' + data.status; } catch (error) { console.error('❌ 前端:后端无响应', error); frontendStatus.textContent = '检查失败'; backendResponse.textContent = '后端无响应'; } } // 绑定事件监听器 sendMessageBtn.addEventListener('click', sendMessage); checkHealthBtn.addEventListener('click', checkHealth); </script> </body> </html>四:部署测试步骤
第1步:启动C++后端服务器
使用cpp-httpLib的测试服务器:(具体参考上一篇:RestfulApi01篇)
第2步:配置前端
修改config.js中的IP地址:
// 获取电脑的局域网IP // Windows: ipconfig // 找到 "无线局域网适配器 WLAN" 下的 IPv4 地址 serverBaseUrl: "http://192.168.31.181:8080", // 替换为你的实际IP第3步:启动Python HTTP服务器
# 在项目目录下运行 python -m http.server 80 --bind 0.0.0.0
第4步:访问测试
电脑测试:
浏览器访问:
http://127.0.0.1应该能看到测试界面
点击按钮测试API
手机测试:
确保手机连接同一个WiFi
手机浏览器访问:
http://192.168.31.181:3000(用你的电脑IP)应该能看到同样的测试界面
点击按钮测试API
手机界面:
五:常见问题解决
问题1:手机访问显示"无法连接到服务器"
解决方法:
# 1. 检查电脑防火墙 netsh advfirewall firewall add rule name="API Test" dir=in action=allow protocol=TCP localport=8000 netsh advfirewall firewall add rule name="Web Server" dir=in action=allow protocol=TCP localport=80 # 2. 检查C++后端绑定地址 # 确保绑定的是 0.0.0.0 而不是 127.0.0.1
问题2:IP地址频繁变化
解决方法:
设置静态IP(推荐):
# Windows设置静态IP netsh interface ip set address name="Wi-Fi" static 192.168.31.181 255.255.255.0 192.168.31.1
路由器绑定IP:
登录路由器管理界面(通常是
http://192.168.31.1)找到DHCP静态分配/地址保留
绑定电脑MAC地址到固定IP
问题3:配置修改不生效
解决方法:
清理浏览器缓存
使用隐私模式访问
重启Python服务器
六:验证测试
成功标志
电脑端:
✅ 页面正常加载
✅ 按钮可点击
✅ API请求成功
✅ 控制台有详细日志
手机端:
✅ 页面正常加载(适配移动端)
✅ 触摸按钮响应正常
✅ API请求成功
✅ 与电脑显示相同结果
验证命令
# 验证后端是否可达 curl http://192.168.31.181:8080/health # 应该返回:{"status":"running"} # 验证前端是否可达 curl http://192.168.31.181:80 # 应该返回HTML页面 # 验证手机网络(在手机上执行) ping 192.168.31.181七:总结
通过这个方案,我们实现了:
配置分离:通过
config.js灵活配置服务器地址跨设备访问:手机和电脑都能测试同一个API
简单部署:只需修改一个配置项
详细反馈:清晰的界面和日志
核心要点:
手机访问需要电脑的局域网IP,不是localhost
电脑和手机必须在同一个WiFi网络
防火墙需要允许相关端口
配置一次,多端通用
现在你可以轻松地在手机和电脑上测试API了,这在移动开发和跨设备测试中非常实用。
下一篇:待定