React Native问题:开发环境POST请求正常,EAS构建APK后失效
React Native Expo 生产构建POST请求失败问题排查与解决
问题描述
React Native Expo应用在npx expo start开发模式下POST请求可正常执行,但通过EAS Build构建APK安装到Android设备后,请求无法正常工作。点击"Done"按钮触发POST请求,预期在按钮下方展示响应文本,但无对应反馈。简化代码如下:
// ...imports and other code... const TypeScreen = () => { const [mole, setMole] = useState(''); const [responseText, setResponseText] = useState(''); const sendPostRequest = async () => { try { const ipAddress = '/*IP*/'; const port = '/*PORT*/'; const endpoint = `http://${ipAddress}:${port}/`; const requestBody = { "key1": mole }; const json = JSON.stringify(requestBody); const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: json, }); if (response.ok) { const responseText = await response.text(); console.log('POST request successful'); console.log('Response Text: ', responseText); setResponseText(responseText); } else { console.error('POST request failed with status:', response.status); } } catch (error) { console.error('Error sending POST request:', error); } }; return ( // ...other components and UI... <TouchableOpacity style={styles.btnPurple} onPress={sendPostRequest} > <Text style={styles.buttonTextWhite}>Done</Text> </TouchableOpacity> <View style={{ marginTop: 20 }}> <Text style={styles.buttonTextPurple}>Response:</Text> <Text style={styles.buttonTextPurple}>{responseText}</Text> </View> ); }
排查与解决建议
Android明文HTTP限制
Android API 28及以上默认阻止明文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">你的服务器IP/域名</domain> </domain-config> </network-security-config> - 在
android/app/src/main/AndroidManifest.xml的<application>标签添加属性:android:networkSecurityConfig="@xml/network_security_config"
- 在项目根目录创建
服务器地址可达性
开发模式下设备与服务器处于同一局域网可访问内网IP,但生产APK运行时,需确认:- 服务器是否允许公网访问,或设备是否与服务器在同一网络环境
- 代码中使用的IP/域名是设备可正常访问的地址,避免使用
localhost或127.0.0.1
网络权限确认
检查app.json或app.config.js中是否配置了网络权限,Expo默认会添加,但手动修改后可能丢失:{ "expo": { "android": { "permissions": ["INTERNET"] } } }生产环境日志捕获
开发环境的console.log无法直接查看,可通过以下方式定位错误:- 运行
adb logcat *:S ReactNative:V ReactNativeJS:V查看Android设备上的React Native相关日志 - 修改代码将错误信息展示到UI:
catch (error) { console.error('Error sending POST request:', error); setResponseText(`请求失败: ${error.message}`); }
- 运行
HTTPS证书信任问题
若服务器使用HTTPS,需确保证书为正规CA颁发,自签名证书会被Android生产环境拦截,需额外配置信任该证书。
内容的提问来源于stack exchange,提问作者MA_Dev
相关产品推荐
相关产品推荐

