如何在Expo/React Native中访问本地运行的API?
解决Expo Web访问本地FastAPI的跨域问题
核心原因
这是浏览器的**跨域资源共享(CORS)**限制导致的:Expo Web运行在http://localhost:19006,你的FastAPI服务在http://localhost:8000,两个端口属于不同源,浏览器会默认阻止这类跨域请求,除非后端明确允许该源的访问权限。
解决方案一:给FastAPI添加CORS中间件
这是最直接且可靠的解决方法,通过后端配置解除跨域限制:
- 在FastAPI项目中添加CORSMiddleware配置,示例代码如下:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 配置允许访问的前端源,添加Expo Web的地址 origins = [ "http://localhost:19006", # 可选:添加本机局域网IP对应的Expo地址,方便其他设备测试 "http://192.168.x.x:19006", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], # 允许所有HTTP请求方法 allow_headers=["*"], # 允许所有请求头 ) # 你的API路由示例 @app.get("/api/profile") async def get_profile(): return {"name": "Demo User", "email": "demo@example.com"}
- 重启FastAPI服务后,Expo Web的fetch请求即可正常访问接口。
解决方案二:使用本机局域网IP替换localhost
部分环境下localhost可能存在解析问题,可通过以下方式调整:
- 修改FastAPI的启动命令,让服务绑定到所有网卡(允许局域网访问):
uvicorn main:app --host 0.0.0.0 --port 8000
- 替换Expo代码中的请求地址为本机局域网IP(比如
192.168.1.100,需替换为你实际的IP):
const response = await fetch('http://192.168.1.100:8000/api/profile', { method:'Get', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, });
额外检查项
- 确认FastAPI服务正常运行,端口
8000未被其他程序占用; - 开发环境可临时关闭本地防火墙,或添加规则允许
8000端口的入站请求。
内容的提问来源于stack exchange,提问作者Jacob Liddy
相关产品推荐
相关产品推荐

