React请求FastAPI后端返回405 Method Not Allowed问题求助
问题分析与解决方案
核心原因:跨域资源共享(CORS)未配置
前端与后端运行在不同端口(比如React默认3000端口,FastAPI默认8000端口),属于跨域请求场景。浏览器会先发送OPTIONS预检请求验证后端是否允许跨域,而FastAPI默认未配置CORS中间件,无法处理OPTIONS请求,因此返回405 Method Not Allowed。而FastAPI自带的UI测试(/docs或/redoc)与后端同域,不存在跨域限制,所以测试可以正常运行。
解决方案:添加CORS中间件
在FastAPI后端代码中添加CORS配置,允许前端所在域名的跨域请求:
from fastapi import FastAPI, HTTPException, Depends, Request from pydantic import BaseModel from typing import List, Annotated # 导入CORS中间件 from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 配置允许跨域的前端地址,根据你的实际前端端口修改 origins = [ "http://localhost:3000", "http://127.0.0.1:3000", ] # 添加CORS中间件 app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], # 允许所有HTTP方法(包括OPTIONS、POST) allow_headers=["*"], # 允许所有请求头 ) models.Base.metadata.create_all(bind=engine) class UserInfo(BaseModel): username: str password: str # 你的其他业务代码... @app.post("/frontend_testing") async def create_user(req: UserInfo, db: db_dependency): print(f"Username: {req.username}") print(f"Password: {req.password}")
额外排查点
- 确认请求地址一致性:检查前端
fetch的URL是否与后端端点完全匹配,避免拼写错误(比如路径大小写、多余/缺失斜杠)。 - 查看浏览器请求详情:打开浏览器开发者工具→Network标签,确认请求Method为POST、URL正确,且请求头包含
Content-Type: application/json。 - 检查后端路由冲突:确保没有其他路由(比如
@app.get("/frontend_testing"))占用相同路径,导致请求被错误路由。
内容的提问来源于stack exchange,提问作者Avik Samanta
相关产品推荐
相关产品推荐

