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

FastAPI后端无法与React Native连接,报错‘Network Request Failed’

React Native调用FastAPI报Network Request Failed的排查方案

1. 配置FastAPI的CORS中间件

FastAPI默认未处理跨域请求,而React Native的fetch会遵循CORS规则,Postman则不受限制。这是最常见的原因,你需要给FastAPI添加CORSMiddleware,并且必须开启allow_credentials=True(因为你的RN请求里用了credentials: 'include'):

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 允许的源,根据你的RN调试环境填写,比如本地模拟器或真机地址
allowed_origins = [
    "http://localhost:8081",
    "http://172.20.10.2:8081",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,  # 不能用通配符*,否则credentials不生效
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 你的/signup接口示例
@app.post("/signup")
async def signup(user_info: dict):
    # 业务逻辑
    return {"status": "ok"}

如果不确定RN的源,可临时用allow_origin_regex=r".*"测试,但生产环境务必指定具体源。

2. 确保FastAPI绑定到局域网可访问地址

FastAPI默认绑定127.0.0.1,仅本机可访问,RN设备(模拟器/真机)无法连接。启动服务时要绑定到0.0.0.0:

uvicorn main:app --host 0.0.0.0 --port 8000

同时确认服务器的局域网IP确实是172.20.10.2,可通过服务器终端执行ifconfig(Linux/macOS)或ipconfig(Windows)查看。

3. 验证网络连通性

在RN设备上ping服务器IP172.20.10.2,如果不通,说明网络存在问题:

  • 确认服务器和RN设备在同一Wi-Fi网络下
  • 检查服务器防火墙是否开放了8000端口
  • 排查路由器是否限制了设备间的通信

4. 核对请求参数格式

虽然Postman调用正常,仍需确认RN发送的userInfo结构与FastAPI接口期望一致。可在FastAPI接口中添加日志打印请求体,排查数据格式问题:

from fastapi import FastAPI, Request

@app.post("/signup")
async def signup(request: Request):
    received_data = await request.json()
    print("接收到的请求体:", received_data)
    # 后续处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:30:21