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

React Native应用同一网络下Fetch笔记本NestJS API失败求助

解决React Native调用本地API时的Network request failed问题

核心问题分析

你遇到的问题确实和HTTP协议配置、React Native的平台安全限制直接相关:

  1. 请求URL缺少http://前缀,导致React Native无法正确解析网络协议
  2. Android/iOS的新版本默认限制明文HTTP请求,需要针对性配置

具体修复步骤

1. 补全请求URL的协议前缀

直接使用IP-address-of-my-laptop:3000/movements会让React Native无法识别请求类型,必须添加http://前缀:

// 错误写法
fetch('192.168.x.x:3000/movements')

// 正确写法
fetch('http://192.168.x.x:3000/movements')

2. 处理Android的HTTP安全限制

Android 9及以上默认禁止明文HTTP请求,需修改项目配置允许指定IP的请求:

  • 新建或打开android/app/src/main/res/xml/network_security_config.xml,添加内容:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">你的笔记本IP地址</domain>
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>
  • 在android/app/src/main/AndroidManifest.xml的<application>标签中添加配置引用:
android:networkSecurityConfig="@xml/network_security_config"

3. 处理iOS的HTTP安全限制

iOS默认阻止明文HTTP请求,需修改Info.plist:

  • 打开ios/[你的项目名]/Info.plist,添加以下键值对:
<key>NSAppTransportSecurity</key>
<dict>
    <!-- 开发环境临时允许所有HTTP请求 -->
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <!-- 上线前建议替换为更安全的域名白名单配置 -->
    <!-- <key>NSExceptionDomains</key>
    <dict>
        <key>你的笔记本IP地址</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSAllowsArbitraryLoads</key>
            <true/>
        </dict>
    </dict> -->
</dict>

4. 额外验证项

  • 确保笔记本和平板连接同一WiFi网络
  • 关闭笔记本防火墙,或在防火墙上允许3000端口的入站请求
  • 确认NestJS服务监听0.0.0.0而非localhost,否则仅能本地访问:
// main.ts中修改监听配置
await app.listen(3000, '0.0.0.0');

内容的提问来源于stack exchange,提问作者Mal d'Aurore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 03:16:01