React Native中POST图片预测接口返回400错误求助
React Native 图片上传返回400错误的解决方案
核心问题分析
你的代码里有两个关键错误导致接口返回400:
- Axios拦截器强制设置了错误的Content-Type:上传
FormData时,Axios会自动生成multipart/form-data类型并添加正确的boundary参数,但你的拦截器把所有请求的Content-Type硬改成了application/json,后端无法解析FormData格式的请求,直接返回400。 - FormData文件参数格式及函数冗余问题:React Native中FormData对文件参数的格式有特定要求,同时
getPredication函数存在不必要的Promise嵌套。
具体修复步骤
1. 修改Axios拦截器,适配FormData请求
修改拦截器代码,仅在非FormData请求时设置JSON类型的请求头:
axios.interceptors.request.use( async config => { let request = config; // 仅当请求体不是FormData时,设置JSON格式的请求头 if (!(config.data instanceof FormData)) { request.headers = { 'Content-Type': 'application/json', Accept: 'application/json', }; } else { // 上传FormData时,让Axios自动处理Content-Type(会自动添加boundary) delete request.headers['Content-Type']; } request.url = configureUrl(config.url); return request; }, error => Promise.reject(error), );
2. 优化图片上传请求逻辑
简化getPredication函数的冗余Promise嵌套,同时确保FormData的文件参数格式符合后端要求:
const getPredication = async params => { const bodyFormData = new FormData(); // 确保文件类型为标准MIME格式,避免后端解析失败 const fileMimeType = params.type || 'image/jpeg'; bodyFormData.append('file', { uri: params.uri, name: params.name || 'uploaded-image.jpg', type: fileMimeType, }); const url = 'https://us-central1-potato-disease-382301.cloudfunctions.net/predict'; return axios.post(url, bodyFormData); };
3. 修正相机拍照后的逻辑错误
openCamera中错误调用了setResult,应该改为触发getResult来发起预测请求:
const openCamera = async () => { launchCamera(options, response => { // ... 其他判断逻辑 else { const uri = response?.assets[0]?.uri; const path = Platform.OS !== 'ios' ? uri : 'file://' + uri; // 调用getResult处理图片并发起预测 getResult(path, response); } }); };
额外验证点
- 测试时可以在Axios请求前打印请求配置,确认
Content-Type为multipart/form-data; boundary=xxx格式 - 确保图片选择器返回的
fileName和type字段不为空,若为空则手动补充默认值
内容的提问来源于stack exchange,提问作者rwwa2014
相关产品推荐
相关产品推荐

