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

React Native使用Fetch上传文件报错:Cannot read property 'json' of undefined

解决React Native Fetch上传文件时的Cannot read property 'json' of undefined错误

1. 先校验请求状态,再处理JSON解析

Fetch请求在网络异常、服务器返回5xx/4xx状态时,不会直接触发catch,而是会进入then但返回异常的响应对象。直接调用response.json()就会因响应异常出现这个报错。修改代码先做状态校验:

fetch('你的上传接口地址', {
  method: 'POST',
  body: formData,
})
.then(response => {
  // 先判断请求是否成功
  if (!response.ok) {
    throw new Error(`请求失败,状态码:${response.status}`);
  }
  // 用可选链避免响应为undefined时调用json()
  return response?.json();
})
.then(data => {
  console.log('上传成功', data);
})
.catch(error => {
  console.error('上传出错', error);
});

2. 确认FormData构造符合要求

上传文件的FormData字段名必须和服务端接收的名称完全匹配,同时要正确设置文件的URI、名称和MIME类型:

const formData = new FormData();
// 注意:file字段名要和服务端代码里的接收参数名一致
formData.append('file', {
  uri: 你的文件本地URI, // 比如从ImagePicker获取的uri
  name: 'test.jpg',
  type: 'image/jpeg',
});
// 附带其他参数
formData.append('user_id', '12345');

3. 排查服务端响应格式

如果服务端处理完上传后没有返回合法的JSON(比如返回空内容、HTML页面),调用response.json()也会报错。可以先改成response.text()查看返回内容:

.then(response => {
  if (!response.ok) throw new Error('请求失败');
  return response.text();
})
.then(text => {
  console.log('服务端返回内容:', text);
  // 尝试解析JSON,失败则处理文本内容
  try {
    const data = JSON.parse(text);
    console.log('解析后的JSON:', data);
  } catch (e) {
    console.log('返回内容不是JSON格式', text);
  }
})

4. 检查基础网络与配置

  • 安卓项目要确保AndroidManifest.xml中添加了网络权限:<uses-permission android:name="android.permission.INTERNET" />
  • 本地测试时,不要用localhost,改用电脑的局域网IP,否则模拟器/真机无法访问服务端

5. 核对服务端代码逻辑

从你提供的服务端截图来看,要确认:

  • 服务端是否正确配置了multipart/form-data类型请求的解析(比如Node.js用multer、Java用MultipartFile)
  • 服务端在上传成功/失败时,是否都能返回合法响应,没有因未处理的异常导致无响应返回

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:15:47