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

FastAPI配置CORSMiddleware后仍出现CORS跨域请求报错求助

CORS配置后仍报错的排查与解决

前端代码

const data = { 
      text: text,
      translateTo: translateTo,
    };

await fetch("http://localhost:8000/translate", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
})

后端代码

# 需确保已导入CORSMiddleware
# from fastapi.middleware.cors import CORSMiddleware

origins = [
    "*"
]

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

@app.post("/translate")
async def translate(text: str = Body(), translateTo: str = Body()) -> str:
    return apiTranslateLang(text, translateTo)

问题描述

已修正变量名并为后端参数添加Body(),但仍收到CORS错误:

Access to fetch at 'http://localhost:8000/translate' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

尽管设置了允许所有源,仍无法解决该问题。

排查与解决步骤

  • 确认CORSMiddleware导入:后端代码必须先导入CORSMiddleware,否则中间件不会生效,添加代码:from fastapi.middleware.cors import CORSMiddleware
  • 检查中间件加载顺序:app.add_middleware(CORSMiddleware, ...)必须在所有路由注册(比如@app.post)之前执行,否则路由不会应用CORS配置
  • 重启后端服务:修改CORS配置后必须重启服务,新配置才会生效
  • 验证预检请求处理:带Content-Type: application/json的POST请求会触发OPTIONS预检,可通过浏览器开发者工具查看OPTIONS请求的响应头是否包含Access-Control-Allow-Origin
  • 排查其他中间件干扰:如果存在其他自定义中间件,检查是否覆盖或移除了CORS响应头

内容的提问来源于stack exchange,提问作者Jaewon Choi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:40:31