Azure静态应用调用Web App API时遇CORS错误(已配置中间件)
在Azure部署的静态应用调用Azure Web App部署的FastAPI接口时,已添加CORSMiddleware但仍触发CORS错误,错误信息如下:
Access to fetch at 'https://itemapp.azurewebsites.net//items/list' from origin 'https://thankful-river-01992e00f.3.azurestaticapps.net' 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.
使用的FastAPI代码:
from fastapi import FastAPI from db import Base,engine from item import router from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "https://thankful-river-01992e00f.3.azurestaticapps.net/" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(router, prefix="/items") #create all tables Base.metadata.create_all(bind=engine)
原因1:Origin地址末尾斜杠不匹配
FastAPI的CORSMiddleware对Origin采用精确匹配,你的origins列表里地址末尾带斜杠/,但实际请求的Origin是不带斜杠的https://thankful-river-01992e00f.3.azurestaticapps.net,匹配失败导致未返回CORS响应头。
解决办法
修改origins列表,去掉地址末尾的斜杠:
origins = [ "https://thankful-river-01992e00f.3.azurestaticapps.net" ]
原因2:请求URL存在重复斜杠
错误信息中的请求URL是https://itemapp.azurewebsites.net//items/list,重复的//可能导致FastAPI路由匹配异常,CORS中间件未被正确触发,无法返回响应头。
解决办法
修正前端请求代码中的URL为https://itemapp.azurewebsites.net/items/list,确保路径仅用单个斜杠分隔。
原因3:Azure Web App自带CORS配置冲突
Azure Web App的配置 > CORS模块如果设置了规则,会优先于FastAPI中间件生效,两者冲突时会导致CORS头异常。
解决办法
登录Azure门户进入目标Web App,在网络 > CORS页面清空所有配置项,完全交由FastAPI的CORSMiddleware处理CORS逻辑。
原因4:中间件加载顺序异常(代码潜在风险)
如果app.add_middleware的代码位置在路由注册之后,部分路由请求可能无法触发CORS中间件。
解决办法
确保app.add_middleware(CORSMiddleware, ...)的代码始终在app.include_router之前(当前代码顺序正确,后续调整代码时需注意)。
内容的提问来源于stack exchange,提问作者av.coder

