You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native用FormData发POST请求遇JSON解析错误及400响应

React Native多图上传POST请求报错排查与解决

问题场景

在React Native中使用FormData发送包含多张图片的POST请求时出现异常:

  • API返回400状态码
  • catch块捕获JSON解析错误:[SyntaxError: JSON Parse error: Unexpected token: N]
  • 该API在Postman中可正常调用,单图上传无问题,仅多图上传时出错

现有代码

let form = new FormData();

form.append('img1', imgArray[0]);
form.append('img2', imgArray[1]);
form.append('img3', imgArray[2]);
form.append('price', selectedprice);
form.append('seller_id', id);
form.append('type', selectedvalue);
form.append('category', 'care');
form.append('from_date', startdate);
form.append('to_date', enddate);
form.append('discription', description);
console.log('form data====>', form);

var requestOptions = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'content-type': 'multipart/form-data',
  },
  body: form,
  redirect: 'follow',
};


fetch('http://base_url/api/upload-products', requestOptions)
  .then((response) =>
    response.json()
  ).then(res => console.log('UPLOAD res===>', res))
  .catch(error =>
    console.log('error==catch>', error));
});

报错信息

[SyntaxError: JSON Parse error: Unexpected token: N]

当前FormData结构

{"_parts": [["img1", "file:///data/user/0/com.appName/cache/rn_image_picker_lib_temp_7eb48acb-2b5e-4ed9-9b20-b7d8293001cd.jpg"], ["img2", "file:///data/user/0/com.appName/cache/rn_image_picker_lib_temp_a8241f47-2d9c-4717-8994-e711a8f22dad.jpg"], ["img3", "file:///data/user/0/com.appName/cache/rn_image_picker_lib_temp_b9a00c94-03de-43eb-ac08-1e4a3a38a22b.jpg"], ["price", "79"], ["seller_id", "65c71746fcf33d49d3334d10"], ["type", "machine"], ["category", "health care"], ["from_date", "17-04-2024"], ["to_date", "17-04-2024"], ["discription", "Ns"]]}

Postman请求情况

Postman中使用form-data格式,img1/img2/img3设为File类型,其他参数为Text类型,可正常调用API。

解决建议

1. 修正图片的FormData格式

React Native中直接传递file://路径无法被后端正确解析为文件,需要将图片包装为符合规范的对象:

// 遍历处理每张图片
imgArray.forEach((imgPath, index) => {
  const imgKey = `img${index + 1}`;
  form.append(imgKey, {
    uri: imgPath,
    type: 'image/jpeg', // 根据实际图片类型调整,如image/png
    name: `${imgKey}.jpg` // 自定义文件名,供后端识别
  });
});

注:如果使用react-native-image-picker,返回结果自带uri/type/fileName,可直接复用这些字段

2. 移除手动设置的Content-Type

使用FormData作为请求体时,React Native会自动生成包含boundary的正确multipart/form-data请求头,手动设置会覆盖默认值导致后端解析失败:

var requestOptions = {
  method: 'POST',
  headers: {
    Accept: 'application/json'
    // 移除 'content-type': 'multipart/form-data'
  },
  body: form,
  redirect: 'follow',
};

3. 先判断响应状态再解析JSON

后端返回400时,响应内容可能不是JSON格式(如纯文本错误信息),直接调用response.json()会触发解析错误,建议先校验状态:

fetch('http://base_url/api/upload-products', requestOptions)
  .then((response) => {
    if (!response.ok) {
      return response.text().then(text => { 
        throw new Error(`HTTP错误!状态码: ${response.status}, 响应内容: ${text}`); 
      });
    }
    return response.json();
  })
  .then(res => console.log('UPLOAD res===>', res))
  .catch(error => console.log('error==catch>', error));

4. 校验参数一致性

对比Postman参数,修正不一致的地方:

  • 代码中category值为'care',但FormData显示为'health care',需和Postman保持一致
  • 检查字段名拼写:discription应为description,后端可能依赖正确的字段名解析

内容的提问来源于stack exchange,提问作者Ramanjeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 18:03:12