FastAPI与ReactJS交互异常:调用接口无响应求助
解决React调用FastAPI接口无响应问题
核心原因:跨域资源共享(CORS)限制
浏览器的同源策略会阻止不同端口/域名的前端页面直接请求后端接口,而Postman这类工具不受此限制,这就是你用Postman正常但React无响应的关键原因。
解决方案:给FastAPI添加CORS中间件
- 确保安装必要依赖(若未安装):
pip install fastapi uvicorn
- 修改FastAPI代码,添加CORS配置:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 允许React本地服务的源(React默认端口是3000) origins = [ "http://localhost:3000", "http://127.0.0.1:3000", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], # 允许所有HTTP方法 allow_headers=["*"], # 允许所有请求头 ) @app.get("/haha") async def read_haha(): return "haha"
- 重启FastAPI服务后,再测试React端的fetch请求即可正常获取响应。
额外检查
- 打开浏览器控制台(F12),查看是否有
Access-Control-Allow-Origin相关的报错,确认问题根源。 - 若你想用已导入的axios替代fetch,可修改React代码中的请求部分:
axios.get('http://127.0.0.1:8000/haha') .then(res => { console.log(res.data); setResponse(res.data); }) .catch(error => console.error(error));
内容的提问来源于stack exchange,提问作者jolaxbeat
相关产品推荐
相关产品推荐

