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

React Native中使用Axios出现Network request failed错误求助

解决React Native中Axios请求"Network request failed"问题

Postman能正常请求但RN里报错,说明接口本身无问题,问题出在RN项目的环境配置或请求细节上,以下是针对性解决方案:

1. 校验API_URL的正确性

  • 本地调试时不要用localhost/127.0.0.1,真机/模拟器无法访问本地环回地址,需替换为电脑的局域网IP(如192.168.3.10)
  • 避免URL拼接错误:如果API_URL结尾带/,拼接后会出现xxx//getCourseLesson的无效路径,推荐用URL对象生成正确地址:
    url: new URL('getCourseLesson', API_URL).href
    

2. iOS平台专属配置

ATS(App Transport Security)限制

iOS默认拦截非HTTPS或证书不合法的请求:

  • 若接口为HTTP,在ios/[项目名]/Info.plist中添加ATS例外:
    <key>NSAppTransportSecurity</key>
    <dict>
      <!-- 全局允许非HTTPS(仅调试用,生产建议用域名白名单) -->
      <key>NSAllowsArbitraryLoads</key>
      <true/>
      <!-- 更安全的域名白名单配置:
      <key>NSExceptionDomains</key>
      <dict>
        <key>你的接口域名</key>
        <dict>
          <key>NSIncludesSubdomains</key>
          <true/>
          <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
          <true/>
        </dict>
      </dict>
      -->
    </dict>
    
  • 若为自签名HTTPS证书,Axios需添加跳过证书校验配置(仅调试用):
    import https from 'https';
    
    axios({
      // ...其他配置
      httpsAgent: new https.Agent({ rejectUnauthorized: false })
    })
    

3. Android平台专属配置

网络权限

确保android/app/src/main/AndroidManifest.xml中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

明文流量限制

Android 9+默认阻止HTTP请求,需配置允许:

  1. 在android/app/src/main/res/xml下新建network_security_config.xml(无xml文件夹则创建):
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <!-- 全局允许HTTP(仅调试用) -->
        <base-config cleartextTrafficPermitted="true" />
        <!-- 域名白名单配置:
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">你的接口域名</domain>
        </domain-config>
        -->
    </network-security-config>
    
  2. 在AndroidManifest.xml的<application>标签中关联配置:
    android:networkSecurityConfig="@xml/network_security_config"
    

4. Axios请求优化与调试

  • 避免async/await和.then/.catch混用,简化代码并添加超时、错误详情打印:
    const getCourseLesson = async () => {
      try {
        const res = await axios({
          method: 'GET',
          url: new URL('getCourseLesson', API_URL).href,
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          timeout: 10000, // 10秒超时
        });
        setLessonList(res.data.data);
      } catch (err) {
        console.log('lesson error:', err.message);
        // 打印更详细的错误信息定位问题
        if (err.response) console.log('响应错误:', err.response.data);
        else if (err.request) console.log('请求无响应:', err.request);
      }
    };
    
  • 调试时关闭代理、VPN,避免网络路由干扰

5. 额外排查手段

  • 用RN调试工具查看Network面板,对比实际发送的URL、请求头与Postman是否一致
  • 终端执行curl -v [完整接口URL],验证接口在本地环境的可用性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:06:15