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

React Native Expo网络错误:Axios及Fetch请求失败问题排查

问题描述

在React Native Expo环境下,使用相同代码请求3个URL,仅第一个https://dummyjson.com/products可正常响应,后两个请求触发AxiosError: Network Error;将Axios替换为Fetch后,又出现TypeError: Failed to fetch错误。尝试请求静态JSON文件也未改善问题,且无法获取更多错误详情。相关代码如下:

axios
  .get("https://dummyjson.com/products", {
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      "Access-Control-Allow-Origin": true,
      "Access-Control-Request-Headers": "Content-Type, x-requested-with",
    },
  })
  .then(response => {
    alert(JSON.stringify(response));
    setbtnDisable(false);
  })
  .catch(err => {
    alert(err);
    setbtnDisable(false);
  });

axios
  .get("http://smart-trd.ir//service/uservice.aspx?UN=NewSignal&ACT=LastOne", {
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      "Access-Control-Allow-Origin": true,
      "Access-Control-Request-Headers": "Content-Type, x-requested-with",
    },
  })
  .then(response => {
    alert(JSON.stringify(response));
    setbtnDisable(false);
  })
  .catch(err => {
    alert(err);
    setbtnDisable(false);
  });

axios
  .get("https://smart-trd.ir/a.json", {
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      "Access-Control-Allow-Origin": true,
      "Access-Control-Request-Headers": "Content-Type, x-requested-with",
    },
  })
  .then(response => {
    alert(JSON.stringify(response));
    setbtnDisable(false);
  })
  .catch(err => {
    alert(err);
    setbtnDisable(false);
  });
排查与解决方案
  • 移除无效请求头:Access-Control-Allow-Origin和Access-Control-Request-Headers是服务端返回的响应头,客户端请求时添加会导致格式异常,直接删除这两个头。
  • 修正协议与URL格式:第二个请求使用的是明文http协议,Expo默认禁止明文HTTP请求(尤其在iOS/Android生产环境),需改为https;同时URL中的双斜杠//要修正为单斜杠/,避免路径解析错误。
  • 验证服务可用性:用浏览器或接口调试工具直接请求目标地址,确认服务能正常返回数据,排除服务端本身故障。
  • 调试环境配置(仅本地开发):如果是本地调试,可在app.json中配置iOS允许任意HTTP请求(生产环境禁用):
    "ios": {
      "infoPlist": {
        "NSAppTransportSecurity": {
          "NSAllowsArbitraryLoads": true
        }
      }
    }
    
  • 获取详细错误信息:将alert(err)改为alert(JSON.stringify(err)),可获取包含状态码、错误堆栈的完整错误详情,帮助定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:05:01