Expo React Native在iPhone端Expo Go中出现Axios网络错误求助
Expo Go实体iPhone上Axios网络错误排查方案
问题背景
使用Expo Go在实体iPhone上运行React Native应用时,Axios请求返回网络错误,后端已开启CORS,电脑浏览器运行正常,更换为电脑IP地址后问题仍存在。
相关代码
useEffect(() => { axios .post('http://127.0.0.1:8081/predict', { image: image, }) .then((response) => { setData(response.data?.predicted_class); switch (response.data?.predicted_class) { case 0: setCircleText('Normal'); setCircleOutlineColor('#36db1d'); break; case 1: setCircleText('Mild'); setCircleOutlineColor('#ffcc00'); break; case 2: setCircleText('Moderate'); setCircleOutlineColor('#ff851b'); break; case 3: setCircleText('Severe'); setCircleOutlineColor('#ff4136'); break; case 4: setCircleText('Proliferative DR'); setCircleOutlineColor('#741b47'); default: setCircleText('Cannot read'); setCircleOutlineColor('#c9c8c5'); } }) .catch((error) => { console.error('Error:', error); }); }, []);
报错截图

排查与解决步骤
- 确认设备处于同一局域网:实体iPhone必须和运行后端服务的电脑连接同一个WiFi网络,否则无法通过局域网IP访问后端。
- 修改后端监听地址:后端服务不能仅监听
127.0.0.1,需改为0.0.0.0,允许接受局域网内其他设备的请求。例如Flask项目设置app.run(host='0.0.0.0'),Node.js项目确保服务器监听0.0.0.0而非localhost。 - 验证IP端口可达性:在iPhone的Safari浏览器中直接访问
http://你的电脑IP:8081,若无法打开或返回数据,说明电脑防火墙拦截了端口,需将8081端口加入防火墙白名单。 - 配置iOS HTTP请求权限:iOS 9+默认限制非HTTPS请求,若后端使用HTTP协议,需在
app.json中添加NSAppTransportSecurity配置:
避免全局开启"ios": { "infoPlist": { "NSAppTransportSecurity": { "NSExceptionDomains": { "你的电脑IP": { "NSIncludesSubdomains": true, "NSAllowsArbitraryLoads": true } } } } }NSAllowsArbitraryLoads,仅针对后端地址放开限制。 - 排查请求数据格式:确保请求中的
image数据格式符合后端要求(如Base64编码),数据格式错误可能导致后端拦截请求,Axios会抛出网络错误。可在catch块中打印响应详情定位问题:.catch((error) => { console.error('Error:', error); if (error.response) { console.log('状态码:', error.response.status); console.log('响应数据:', error.response.data); } });
内容的提问来源于stack exchange,提问作者Rasanga Lakshith
相关产品推荐
相关产品推荐

