React Native打包APK后无法通过Axios请求Django REST API
解决React Native打包APK后无法调用Django REST API的问题
常见排查方向及解决方案
1. 检查Android网络权限
打包后的APK需要明确声明INTERNET权限,在android/app/src/main/AndroidManifest.xml中添加:
<uses-permission android:name="android.permission.INTERNET" />
2. 处理明文HTTP限制(Android 9+)
Android 9及以上默认阻止明文HTTP请求,若你的API使用HTTP而非HTTPS,需配置网络安全策略:
- 在
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">你的服务器IP或域名</domain> </domain-config> </network-security-config>
- 在
AndroidManifest.xml的application标签中添加引用:
<application ... android:networkSecurityConfig="@xml/network_security_config">
3. 确认API地址的正确性
- 禁止使用
localhost或127.0.0.1,需使用服务器的局域网IP(确保手机与服务器在同一网络)或公网IP/域名。 - 排查
ipAddress变量在打包后的取值是否正确,可临时修改错误提示输出完整请求地址,比如将setError('error in fetching')改为setError(错误地址:${apiUrl}),验证地址是否有效。
4. 优化错误捕获逻辑
当前错误处理过于模糊,无法定位具体问题,修改fetchDataFromAPI的catch块:
catch (error) { // 捕获具体错误信息,便于排查 const errorMsg = error.response ? `请求失败:${error.response.status} ${error.response.data}` : error.message || '网络请求错误'; setError(errorMsg); setData(null); }
额外提示
- 打包前可使用
expo build:android --profile preview生成预览包测试,快速定位问题。 - 若服务器部署在公网,优先使用HTTPS,避免明文HTTP的限制和安全风险。
内容的提问来源于stack exchange,提问作者ClownBunny
相关产品推荐
相关产品推荐

