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

FastAPI部署至Render.com遇307重定向且CORS配置冲突求助

解决FastAPI部署到Render.com出现307重定向及CORS问题

问题分析

  1. 307临时重定向原因:你的FastAPI路由定义为/movie_predict/(带尾部斜杠),但在Render上请求的是/movie_predict(不带斜杠)。FastAPI默认会对路径尾部斜杠不匹配的请求返回307重定向,引导至带斜杠的路径。本地环境中浏览器会自动跟随重定向,所以你看到的是最终200状态码,直接调用接口时才会暴露307问题。
  2. CORS问题:之前调整代码导致CORS配置失效,需确保CORSMiddleware配置正确。

解决方案

方案1:统一路由与请求路径的尾部斜杠

修改路由定义,去掉尾部斜杠,让路由和请求路径完全匹配:

@app.get("/movie_predict")  # 移除尾部斜杠
async def simple_recommendation(movie_name: str = Query(..., description="Name of the movie")):
    try:
        movies_list = simple_movie_recommendation(movie_name)
        return JSONResponse(
            status_code=200,
            content={'movies': movies_list},
        )
    except Exception as e:
        print_exception(e)
        return JSONResponse(
            content={'message': 'Internal server error'},
            status_code=500
        )

若想同时支持带斜杠和不带斜杠的请求,可在初始化FastAPI时关闭自动重定向:

app = FastAPI(redirect_slashes=False)

方案2:保持路由带斜杠,修正请求路径

如果不想修改路由,确保在Render上调用接口时使用带尾部斜杠的路径:
https://example-url-not-real/movie_predict/?movie_name=Shrek

确保CORS配置有效

保留当前CORSMiddleware配置,它已允许所有来源、方法和头部,可解决React应用跨域问题:

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["POST", "GET"],
    allow_headers=["*"],
    expose_headers=["*"]
)

安全优化建议:若React应用已部署到固定域名,可将allow_origins改为具体域名(如["https://your-react-app-domain.com"]),避免过度开放权限。

验证步骤

  1. 将修改后的代码重新部署到Render.com
  2. 按对应方案调用接口,检查返回状态码是否为200
  3. 验证React应用能否正常访问接口

内容的提问来源于stack exchange,提问作者Victor Resende

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:58:16