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

Quart集成Azure Application Insights后出现CORS错误求助

问题:添加Azure Application Insights后Quart后端CORS错误复现

原本通过quart_cors库已经解决了Quart后端的CORS问题,功能一切正常。但在集成Microsoft Azure Application Insights之后,前端又出现了CORS错误。

后端核心配置代码

app = cors(app, allow_origin="*", allow_headers=["Content-Type"])

Routes.py中的请求钩子代码

@app.before_request
async def before_request():
    # 开始追踪请求
    print("TEST")
    request.tracer = Tracer(exporter=AzureExporter(connection_string=os.getenv('CONNECTION_STRING_APPLICATION_INSIGHTS')), sampler=ProbabilitySampler(rate=1.0))
    request.tracer.span(name=request.path)

@app.after_request
async def after_request(response):
    # 结束追踪请求
    print("TEST 2")
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    request.tracer.finish()
    
    return response

前端CORS错误截图

前端CORS错误提示


解决方案

问题根源是OPTIONS预检请求未被正确处理:

  1. 浏览器发送OPTIONS预检请求时,before_request钩子会强制初始化Tracer,但这类请求不需要追踪,甚至可能因Tracer初始化逻辑导致响应头未正确设置、请求提前出错。
  2. quart_cors已经自动处理CORS头,手动在after_request重复设置反而可能引发冲突。

修复代码

修改Routes.py中的请求钩子逻辑:

@app.before_request
async def before_request():
    # OPTIONS预检请求跳过追踪逻辑
    if request.method == 'OPTIONS':
        return
    print("TEST")
    request.tracer = Tracer(exporter=AzureExporter(connection_string=os.getenv('CONNECTION_STRING_APPLICATION_INSIGHTS')), sampler=ProbabilitySampler(rate=1.0))
    request.tracer.span(name=request.path)

@app.after_request
async def after_request(response):
    # 仅针对非OPTIONS请求结束追踪
    if request.method != 'OPTIONS':
        print("TEST 2")
        request.tracer.finish()
    return response

保留quart_cors的原有配置即可,无需手动添加CORS响应头,避免重复配置引发的冲突。


内容的提问来源于stack exchange,提问作者Matheus Weber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 09:22:40