在Expo环境的React Native Android中调用Axios遇网络错误求助
解决Expo React Native Android中Axios网络错误问题
在Expo环境的React Native Android项目中使用Axios发起API调用时触发Network Error,控制台报错信息如下:
Network Error at node_modules\axios\lib\core\AxiosError.js:3:0in <global> at node_modules\axios\lib\adapters\xhr.js:138:8 in handleAbort at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:647:10 in setReadyState at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:396:6 in didCompleteResponse at node_modules\react-native\Libraries\vendor\emitter_EventEmitter.js:150:10 in EventEmitter#emit at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:417:4 in callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:114:6 in guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:368:10 in guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:4 in callFunctionReturnFlushedQueue
已尝试的排查步骤
- 将API链接中的localhost替换为个人本地IP地址及Android模拟器默认回环地址10.0.2.2
- 检查并确认AndroidManifest.xml中已添加
<uses-permission android:name="android.permission.INTERNET"/>网络权限
针对性解决方案建议
确认Expo网络访问规则
Expo Go在Android上对本地网络请求有特殊限制,确保API服务和调试设备(模拟器/真机)处于同一Wi-Fi网络;若API运行在本地,启动服务时绑定0.0.0.0而非127.0.0.1,保证服务对外可见,比如后端启动命令改为npm start --host 0.0.0.0(根据后端框架调整)。检查Axios配置细节
确认baseURL没有遗漏端口号或协议错误;添加超时配置避免请求中断:const axiosInstance = axios.create({ baseURL: 'http://你的IP:端口', timeout: 10000, // 10秒超时 headers: { 'Content-Type': 'application/json', }, });临时关闭请求/响应拦截器,排查是否是拦截器修改请求导致的错误。
适配Android版本与设备类型
Android 9及以上版本若使用http协议,需在app.json中添加网络安全配置允许明文请求:{ "expo": { "android": { "networkSecurityConfig": { "domainUrls": ["http://你的IP地址/*"] } } } }若使用Genymotion模拟器,尝试用
10.0.3.2替代10.0.2.2;真机调试时,检查防火墙是否阻止了API端口的访问。排查API服务可用性
用手机浏览器直接访问API地址,确认服务能正常响应;检查后端是否设置了跨域限制,若有需允许Expo应用的IP或域名访问。更换Axios适配器
安装axios-adapter-react-native替换默认XHR适配器,解决Expo环境下的兼容性问题:npm install axios-adapter-react-native配置Axios:
import axios from 'axios'; import axiosAdapter from 'axios-adapter-react-native'; const axiosInstance = axios.create({ adapter: axiosAdapter, baseURL: 'http://你的IP:端口', });
内容的提问来源于stack exchange,提问作者Luiz Carlos Gandra
相关产品推荐
相关产品推荐

