React Native调用无SSL远程API报‘network request failed’求助
解决React Native调用无SSL远程API的"network request failed"问题
修正URL协议
你代码里用了https://,但你的API是无SSL的,必须改成http://——这是最容易忽略的错误,用HTTPS请求无SSL的服务直接会导致连接失败。完善Android网络配置
除了android:usesCleartextTraffic="true",还要做这些:- 确保
AndroidManifest.xml添加了网络权限:<uses-permission android:name="android.permission.INTERNET" /> - 在
res/xml目录新建network_security_config.xml,内容如下:<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> </trust-anchors> </base-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">xx.xxx.xxx.xxx</domain> <!-- 替换成你的API IP --> </domain-config> </network-security-config> - 在
AndroidManifest.xml的<application>标签里引用这个配置:android:networkSecurityConfig="@xml/network_security_config"
- 确保
配置iOS允许非HTTPS请求
iOS默认拦截非HTTPS请求,需要修改Info.plist:- 添加
NSAppTransportSecurity字典,开启全局允许(快速测试用):<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> - 或者针对你的API IP做精准配置(更安全):
<key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>xx.xxx.xxx.xxx</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> </dict>
- 添加
排查网络端口可达性
用手机浏览器直接访问http://xx.xxx.xxx.xxx:50000/b1s/v1/Login,确认设备所在网络没有防火墙/路由器拦截50000端口。优化fetch请求参数
GET请求不需要body参数,建议去掉避免潜在问题:fetch('http://xx.xxx.xxx.xxx:50000/b1s/v1/Login', { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson) }).catch((error) => { console.error(error); });
内容的提问来源于stack exchange,提问作者user28491502
相关产品推荐
相关产品推荐

