React Native真机本地Get请求失效,模拟器与浏览器正常求助
解决React Native真机无法访问本地网络请求的问题
按以下步骤逐一排查:
1. 确认设备与服务器在同一局域网
- 确保手机和运行本地服务器的电脑连接同一个WiFi网络
- 重新核对服务器的局域网IP:电脑端用
ipconfig(Windows)或ifconfig/ip addr(Mac/Linux)查看当前IP,确认代码里的192.168.0.100是电脑的真实局域网IP(路由器重启后IP可能变更)
2. 开启错误日志定位问题
你的代码catch块未输出错误信息,先修改代码打印错误:
const test = () => { axios.get('http://192.168.0.100/Power?Power=1') .then(response => { console.log('请求成功:', response.data); }) .catch(error => { console.error('请求失败:', error.message); // 真机可临时用alert查看错误 alert('请求失败: ' + error.message); }); };
通过npx react-native log-android/npx react-native log-ios查看真机日志,或直接看手机上的alert提示,快速定位是网络不通、权限问题还是其他错误。
3. 处理Android明文HTTP限制(Android 9+)
Android 9及以上默认禁止明文HTTP请求,若本地服务器用HTTP,需配置网络安全策略:
- 在
android/app/src/main/res/xml目录(无则新建)创建network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">192.168.0.100</domain> <!-- 多IP/域名可继续添加 --> </domain-config> </network-security-config>
- 在
android/app/src/main/AndroidManifest.xml的application标签添加属性:
<application ... android:networkSecurityConfig="@xml/network_security_config"> ... </application>
修改后重新编译:npx react-native run-android
4. 处理iOS ATS限制
iOS默认要求HTTPS请求,需在Info.plist中添加例外:
- 打开
ios/[你的项目名]/Info.plist,添加配置:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <false/> <key>NSExceptionDomains</key> <dict> <key>192.168.0.100</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSAllowsArbitraryLoads</key> <true/> </dict> </dict> </dict>
开发阶段也可临时允许所有HTTP请求(上架App Store时需移除):
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
修改后重新编译:npx react-native run-ios
5. 检查电脑防火墙设置
确保电脑防火墙未阻止服务器端口的局域网访问:
- Windows:打开Windows Defender防火墙,添加允许服务器程序/对应端口接收局域网连接的规则
- Mac:打开系统设置→网络→防火墙→选项,允许服务器程序接收连接
内容的提问来源于stack exchange,提问作者Timur Portman
相关产品推荐
相关产品推荐

