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

如何解决FastAPI与Vue.js间的CORS跨域请求错误?

CORS错误:Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response

问题描述

前端发起POST请求时触发CORS错误,具体错误信息:

Access to XMLHttpRequest at 'https://blabla.execute-api.blabla.amazonaws.com/prod/sondage/croisement/test/' from origin 'https://master.test.amplifyapp.com' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

环境配置

  • 后端:EC2部署的FastAPI服务器
  • 前端:Amplify部署的Vue.js应用
  • 中间层:AWS API Gateway(因前端不允许直接访问HTTP服务器,故引入)

异常现象

  • 登录接口(POST请求)完全正常
  • 仪表盘的GET请求正常,但POST请求触发上述CORS错误

后端CORS配置

origins = [
"https://master.test.amplifyapp.com/",
"https://master.test.amplifyapp.com",
"https://master.test.amplifyapp.com/*",
"https://master.test2.amplifyapp.com",
"https://master.test2.amplifyapp.com/*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*", "Content-Type"],
max_age=3600
)

示例POST路由

app.include_router(authentication.router,
    prefix="/authentication",
                       tags=["authentication"])
app.include_router(sondage.router,
                       prefix="/sondage",
                       tags=["sondage"])


@router.post("/ppt/{name}/", status_code=status.HTTP_201_CREATED)
async def generate_ppt(name: str, param: FilterModel, session: SessionLocal = Depends(get_session),
                          current_user: UserAdminOut = Depends(get_current_user)):

    ad = session.query(Ad).filter(Ad.name == name).first()

    if ad is None:
        return responses.Response(status_code=status.HTTP_404_NOT_FOUND, content=f"Ad {name} pas trouvé")

    dynamic_quiz = session.query(DynamicQuiz).filter(DynamicQuiz.ad_id == ad.id).first()

    if dynamic_quiz is None:
        return responses.Response(status_code=status.HTTP_404_NOT_FOUND, content=f"quizz pour {name} pas trouvé")
    sondages, all_responses = get_all_dynamic_quiz(dynamic_quiz, session)
    ppt = GeneratePpt(enquetes=sondages, all_responses=all_responses, filter = param, title_of_ppt=name.replace(" ", ""), title_of_dir=name.replace(" ", ""), session=session)
    ppt.execute()
    return responses.Response(status_code=status.HTTP_201_CREATED)

补充说明

  • API Gateway通过Postman测试正常,排除网关本身故障
  • 已尝试添加多个域名到CORS origins列表、修改后端路由,均未解决问题

解决方案

1. 修正FastAPI的CORS配置细节

  • 简化allow_headers:["*"]已包含所有请求头,无需重复添加Content-Type,修改为:
    allow_headers=["*"]
    
  • 清理无效的origin条目:FastAPI的CORSMiddleware不支持域名后加通配符路径(如https://master.test.amplifyapp.com/*),也不需要带尾部斜杠,保留纯净域名即可:
    origins = [
        "https://master.test.amplifyapp.com",
        "https://master.test2.amplifyapp.com"
    ]
    

2. 检查API Gateway的CORS配置

浏览器的预检请求(OPTIONS)会严格校验CORS响应头,需确保API Gateway的CORS设置满足:

  • 允许的Origin包含https://master.test.amplifyapp.com(不能用*,因为后端启用了allow_credentials=True)
  • 允许的Headers包含Content-Type或直接设为*
  • 允许的Methods包含OPTIONS, POST, GET
  • 开启Access-Control-Allow-Credentials选项

3. 验证前端请求格式

确保前端POST请求的Content-Type为application/json(FastAPI默认解析的请求体格式),如果使用其他格式(如multipart/form-data),需在CORS配置中明确允许对应头,或调整请求格式。

4. 检查预检请求响应头

在浏览器开发者工具的Network面板中,查看OPTIONS预检请求的响应头,确认:

  • Access-Control-Allow-Headers包含Content-Type
  • Access-Control-Allow-Origin是当前前端域名(而非*)
  • Access-Control-Allow-Credentials为true

5. 排查路由参数解析问题

你的POST路由接收FilterModel类型的参数,要求请求体为JSON格式。如果前端未正确发送JSON数据,可能触发FastAPI的参数解析错误,间接导致CORS异常。可通过浏览器Network面板检查请求体格式是否正确。


内容的提问来源于stack exchange,提问作者Yann-arthur Tcheumani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:47:45