You need to enable JavaScript to run this app. React Native Android端fetch请求报JSON解析错误无法获取结果求助
优惠活动
大模型
产品
解决方案
定价
更多

React Native Android端fetch请求报JSON解析错误无法获取结果求助

React Native Android端fetch POST请求异常问题

问题场景

  • 开发的基于fetch实现POST请求的功能,相同代码在网页端可以正常获取接口返回结果,运行在Android平台时无法得到正常响应。

现有实现代码

async submit() {
    var data = new FormData();
    data.append('nome', this.state.nome);
    data.append('endereco', this.state.endereco);
    data.append('foto', this.state.foto.uri);
    
    const resposta = await fetch("webapiexample.com/create.php", {
        method: 'POST',
        body: data,
    }).then((e) => e.json())
    .catch(function (error) {
        console.log("miss");
        console.log(error);
      });
    console.log(resposta)
}

各端运行结果对比

  1. 网页端正常返回的响应内容:

    {msg: "Inserido com sucesso!", erro: false}

  2. Android真机运行时的控制台输出:

    miss
    undefined
    JSON Parse error: Unrecognized token '<'
    触发错误的调用栈:

    • node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
    • node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
    • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
    • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
    • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
    • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
    • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
    • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
    • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
    • [native code]:null in flushedQueue
    • [native code]:null in invokeCallbackAndReturnFlushedQueue

注:输出中打印的undefined,就是代码末尾console.log的执行结果

错误原因与排查解决方向

报错信息中的JSON Parse error: Unrecognized token '<',本质是代码执行到e.json()做响应解析时,拿到的响应体不是合法JSON格式,而是HTML内容(典型特征为以<开头的页面代码,比如错误提示页、跳转重定向页、拦截返回页),因此JSON解析失败进入catch分支,最终拿到的响应值为undefined。
针对该场景的高频问题点与修正方式:

  • 请求地址未补全协议前缀
    代码中的请求地址为裸域名webapiexample.com/create.php,没有配置https:///http://协议头。网页端浏览器会自动基于当前页面协议补全裸域名,但Android端的原生网络栈不会自动补全裸域名,可能出现路由解析失败,返回HTML格式的本地错误页。
    修正方式:将请求地址替换为带完整协议前缀的格式,例如https://webapiexample.com/create.php。
  • Android端明文HTTP请求被系统拦截
    Android 9.0及以上版本默认禁止应用发起明文HTTP请求,系统会直接拦截对应请求,返回内置的HTML格式拦截提示,完全匹配当前报错特征。
    修正方式:优先将接口服务升级为HTTPS加密访问;测试场景下可在Android应用配置的AndroidManifest.xml文件中,给application节点增加android:usesCleartextTraffic="true"配置,放开明文HTTP请求权限。
  • FormData的文件字段格式不符合React Native规范
    网页端FormData上传文件时,可以直接将File对象塞入append方法,但React Native环境下无法直接把本地文件路径字符串(this.state.foto.uri)作为文件内容传给后端,后端会因为接收到的参数格式不符合预期,返回HTML格式的错误提示页。
    修正方式:调整照片字段的传参格式为React Native规定的文件对象结构:
    // 替换原有直接传uri字符串的写法
    data.append('foto', {
      uri: this.state.foto.uri,
      type: 'image/jpeg', // 与实际图片格式保持一致
      name: 'foto.jpg'    // 与后端预期的文件名规则匹配
    })
    
  • 请求来源校验被后端拦截
    网页端发请求时会附带固定的Origin请求头,若后端配置了来源白名单/跨域拦截规则,Android端发起的请求Origin头与网页端不一致,会被安全规则拦截,返回HTML格式的拦截提示页。可先通过简单的文本请求测试连通性,确认是否被来源规则拦截,对应调整后端白名单配置即可。
  • 排查阶段优化日志打印逻辑
    避免直接对响应做JSON解析,先打印原始响应文本内容,可直观看到返回的是HTML错误页还是其他格式内容,快速定位问题:
    const resposta = await fetch("https://webapiexample.com/create.php", {
        method: 'POST',
        body: data,
    }).then(async (e) => {
      const rawText = await e.text()
      console.log('接口原始返回:', rawText)
      return JSON.parse(rawText)
    }).catch(function (error) {
        console.log("miss");
        console.log(error);
    });
    

内容的提问来源于stack exchange,提问作者Luiz Carlos Coelho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 14:45:08