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

Azure AppInsights致第三方脚本CORS错误,如何禁用XMLHttpRequest插桩?

解决Azure Application Insights插桩XMLHttpRequest导致的第三方脚本CORS错误

问题根源

Azure Application Insights默认会对全局XMLHttpRequest及fetch对象插桩,自动为所有请求添加traceparent请求头用于链路追踪。当第三方脚本(如示例中的HubSpot脚本)向自身域名发起请求时,对方服务器的CORS策略未允许traceparent头,导致预请求(OPTIONS)校验失败,触发CORS错误。

解决方案1:完全禁用Ajax请求跟踪(符合你的需求)

如果你不需要AppInsights跟踪任何Ajax请求,可在初始化配置中添加disableAjaxTracking: true,彻底关闭XMLHttpRequest和fetch的插桩功能,避免自动添加traceparent头。

修改后的初始化代码:

<body>
...
<script>
const appInsights = new ApplicationInsights({
  config: {
    instrumentationKey: SOM_APPINSIGHTS_INSTRUMENTATIONKEY,
    disableAjaxTracking: true // 禁用所有Ajax请求的插桩跟踪
  }
});
appInsights.loadAppInsights(); // 必须调用此方法完成初始化
</script>

<script type="text/javascript" src="https://js.hs-scripts.com/XXX.js"></script>
</body>

解决方案2:仅过滤第三方域名请求(保留自有请求跟踪)

若仍需跟踪自有站点的Ajax请求,可通过correlationHeaderExcludedDomains配置指定无需添加traceparent头的域名列表,跳过第三方域名的插桩处理。

示例配置:

<script>
const appInsights = new ApplicationInsights({
  config: {
    instrumentationKey: SOM_APPINSIGHTS_INSTRUMENTATIONKEY,
    correlationHeaderExcludedDomains: [
      "hubspot.com", // 排除HubSpot相关域名
      "hs-scripts.com"
    ]
  }
});
appInsights.loadAppInsights();
</script>

效果验证

修改配置后重新加载页面,第三方脚本的请求将不再携带traceparent头,预请求可通过对方服务器的CORS校验,请求即可正常执行。

你遇到的Chrome报错示例:
Access to XMLHttpRequest at
'https://api.hubspot.com/livechat-public/v1/message/public?portalId=XXXXXXXX'
from origin 'http://localhost:3333' has been blocked by CORS policy:
Request header field traceparent is not allowed by Access-Control-Allow-Headers in preflight response.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:41:14