axios 和 Azure Application Insights 的问题

Problems with axios and Azure Application Insights

Microsoft 的 NPM 包 @microsoft/applicationinsights-we 在前端使用时将添加 headers 以跟踪跨应用程序不同部分(例如前端、后端、服务等)的调用。

我在前端使用 axios,开箱即用不适用于该包。 disableFetchTracking:falsedisableAjaxTracking:false 都不起作用。我不想把axios换成fetch,因为axios用起来更方便,这样重写也很多

我能做什么?

@microsoft/applicationinsights-web 包确实将相关性 header 注入 axios 调用(通过检测 XMLHttpRequest)。您的应用程序中可能有几个问题的原因:

另一个库破坏了检测

其他东西可能会劫持 XMLHttpRequest object 并影响 AppInsights 检测。一个这样的库是 pace.js,它会覆盖 window.XMLHttpRequest 构造函数,但不会将 opensendabort 添加到它的原型中。 AppInsights 期望这些函数出现在 XMLHttpRequest 的原型中:https://github.com/microsoft/ApplicationInsights-JS/blob/91f08a1171916a1bbf14c03a019ebd26a3a69b86/extensions/applicationinsights-dependencies-js/src/ajax.ts#L330

这是一个有效的 axios + @microsoft/applicationinsights-web 示例:

这是相同的示例,但加载了 pace.js - Request-Id header 未添加:

在 AppInsights 初始化代码之后删除 pace.js 或放置它的脚本标签/导入应该可以解决问题。

Cross-origin 请求

另一种解释可能是前端应用发出 cross-origin 请求,默认情况下 AppInsights 不处理这些请求 - 需要 enableCorsCorrelation: true 配置设置。