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

React Native调用RapidAPI时Fetch请求出现网络失败问题排查

React Native调用RapidAPI接口报错TypeError: Network request failed的排查方案

问题描述

开发React Native应用时,通过Fetch/Axios调用RapidAPI的笑话接口始终报错TypeError: Network request failed,但RapidAPI提供的Python代码可正常运行;修改iOS项目Info.plist中NSAllowsArbitraryLoads为true并重新构建后问题仍未解决,且调用jsonplaceholder接口可正常请求。

示例代码

useEffect(() => {
  fetch("https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes", {
    method: "GET",
    headers: {
      'X-RapidAPI-Key': 'myapi',
      'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'
    }
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => console.log(error));
}, []);

补充测试代码

const url = 'https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes';
const options = {
  method: 'GET',
  headers: {
    'X-RapidAPI-Key': '79274b9cbamsh648fe97da3e476dp167e86jsnb80a57f2cac5',
    'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'
  }
};

// const url = 'https://jsonplaceholder.typicode.com/posts/1';
// const options = {
//   method: 'GET',
//   headers: {
//     'Content-Type': 'application/json',
//     'Dummy-Header': 'TestValue' // Custom dummy header for testing
//   }
// };

fetch(url, options)
  .then(res => res.json())
  .then((resJson) => {
      console.log(resJson)
      resolve()
  })
  .catch((e) => {
    console.log('Error in getAddressFromCoordinates', e)
    resolve()
  })

排查与解决方案

  • 验证API密钥有效性
    检查RapidAPI控制台中该接口的调用额度是否耗尽,密钥是否存在拼写错误(如多空格、字符缺失)。免费版接口通常有调用次数限制,额度用完后会直接拒绝请求,而Python代码可能使用了不同的有效密钥。

  • 核对请求头配置
    确保X-RapidAPI-Key和X-RapidAPI-Host的键名无大小写错误,Host值与接口文档完全一致。例如X-RapidAPI-Key不能写成X-RapidApi-Key,大小写不匹配会导致鉴权失败。

  • 优化iOS ATS配置
    仅设置NSAllowsArbitraryLoads为true可能因缓存或配置优先级问题不生效,可添加针对RapidAPI域名的例外配置:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <false/>
      <key>NSExceptionDomains</key>
      <dict>
        <key>rapidapi.com</key>
        <dict>
          <key>NSIncludesSubdomains</key>
          <true/>
          <key>NSExceptionRequiresForwardSecrecy</key>
          <false/>
        </dict>
      </dict>
    </dict>
    

    修改后需清理Xcode缓存,重新构建项目。

  • 排查网络环境
    公司内网、校园网可能拦截HTTPS请求,设备代理配置错误也会导致请求失败。切换至手机流量或无拦截的WiFi网络,关闭代理工具后重试。

  • 获取详细错误信息
    在catch块中打印完整错误详情:

    .catch((e) => {
      console.log('Error details:', JSON.stringify(e));
      console.log('Error stack:', e.stack);
    })
    

    或使用Charles抓包工具,确认请求是否发送成功、服务器返回的状态码(如401鉴权失败、429请求超限)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:46:02