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

React Native fetch请求在Android设备上无法正常工作求助

React Native 网络请求失败(TypeError: Network request failed)解决思路

问题描述

我碰到这个问题好一阵了,网上能找到的方法都试了,全不管用。报错信息如下:

[Unhandled promise rejection: TypeError: Network request failed]
at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue

网上提到最多的解决方案是设置android:usesCleartextTraffic = true,但我查了React Native文档,也检查了Manifest文件,这个属性已经设为true了。文档相关说明:

On Android, as of API Level 28, clear text traffic is also blocked by default. This behaviour can be overridden by setting android:usesCleartextTraffic in the app manifest file.

我的请求代码如下:

async upload(data: FormData): Promise<ITest> {
  const response = await fetch(`${baseURL}/test/file`, {
    body: data,
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
  });
  return response.json().then(res => res);
},

核心修复方案

1. 修正Content-Type设置错误

你用FormData作为请求体,但手动指定了Content-Type: application/json,这会导致服务器无法正确解析FormData。当使用FormData时,fetch会自动生成包含boundary的multipart/form-data请求头,不需要手动设置。

修改后的代码:

async upload(data: FormData): Promise<ITest> {
  const response = await fetch(`${baseURL}/test/file`, {
    body: data,
    method: 'POST',
    // 移除手动设置的Content-Type
  });
  return response.json();
},

2. 额外排查方向

  • 确认baseURL的可访问性:如果是本地开发环境,不要用localhost,改用电脑的IP地址(模拟器/真机需要能访问到服务器所在的网络)
  • 验证服务器接口:用Postman等工具测试相同的接口和FormData,确认服务器端能正常接收并处理请求
  • 检查Android网络安全配置:如果自定义了network_security_config.xml,确保配置允许目标域名的请求
  • 排除代理干扰:检查模拟器/真机是否开启了代理,代理可能会导致请求无法正常到达服务器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:02:39