React Native 0.70.5提交FormData遇网络错误及Flipper依赖问题
解决React Native 0.70.5中axios提交带图片的FormData网络错误及Flipper依赖问题
一、FormData提交网络错误的解决方案
1. 移除手动设置的Content-Type
axios会自动根据FormData生成包含boundary的正确multipart/form-data请求头,手动设置会丢失boundary,导致服务端无法解析请求。修改后代码:
const res = await axios .post(`${Base_URL}/events`, data, { headers: { 'token': JSON.parse(token) // 移除"Content-Type": "multipart/form-data" } }) .then(response => console.log(response)) .catch(error => console.log(error.response?.data || error.message));
2. 统一图片URI格式
React Native中iOS和Android的URI格式存在差异:
- iOS通常为
file://开头的路径 - Android可能返回
content://格式的URI,axios无法直接识别
可以通过以下方式处理:
import RNFS from 'react-native-fs'; import { Platform } from 'react-native'; // 处理图片URI let imageUri = secondImage[0].uri; if (Platform.OS === 'android' && imageUri.startsWith('content://')) { const fileName = displayImage; const filePath = `${RNFS.DocumentDirectoryPath}/${fileName}`; await RNFS.copyFile(imageUri, filePath); imageUri = `file://${filePath}`; } data.append('displayImage', { uri: imageUri, name: displayImage, type:'image/jpeg' });
3. 验证图片参数正确性
- 确保
displayImage变量是有效的文件名(如"test.jpg") - 确认
type与图片实际格式匹配(如PNG图片需改为image/png)
4. 调试请求
使用Flipper的Network插件或Charles抓包工具,查看请求的实际格式、参数是否完整,排查服务端是否能正常接收数据。
二、Flipper版本依赖错误的解决方案
React Native 0.70.x对Flipper版本有兼容要求,0.46.0版本过于老旧已从maven仓库移除,建议:
- 使用RN官方推荐的兼容版本:React Native 0.70.x对应的Flipper推荐版本为
0.125.0(即你最初使用的版本),无需降级。 - 若需调整版本,选择0.120.0~0.144.0之间的版本(需确认兼容),修改
android/gradle.properties中的FLIPPER_VERSION。 - 清理缓存重新构建:
# 清理Android构建缓存 cd android && ./gradlew clean # 清理Node依赖缓存 rm -rf node_modules package-lock.json yarn.lock npm install # 或 yarn install
内容的提问来源于stack exchange,提问作者Precious Oghenevwarho
相关产品推荐
相关产品推荐

