Fiori launchpad集成Google Tag Manager时出现CORS错误如何解决?
问题根因
该报错触发的核心逻辑是浏览器CORS策略的限制,具体报错信息如下:
Access to XMLHttpRequest at 'https://www.google-analytics.com/j/collect?........' from origin 'https://firoi.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
单独运行UI5应用时,Google Analytics的上报请求默认未开启withCredentials配置,因此可以正常接收Google侧返回的通配符跨域头;但Fiori Launchpad运行时会默认给所有跨域请求开启withCredentials属性要求携带凭据,和Google侧返回的通配符跨域头冲突,因此触发拦截。
可行解决方案
方案1:关闭GA上报请求的凭据携带配置
在GTM的Google Analytics标签配置中添加自定义字段transport.withCredentials,值设为false,强制上报请求不携带跨域凭据,匹配Google侧的跨域响应规则。如果直接调用gtag API,可以在初始化时添加以下配置:gtag('set', 'transport', { withCredentials: false });方案2:更换上报传输方式为beacon
配置Google Analytics使用navigator.sendBeacon接口上报数据,该接口不会触发CORS预检请求,也不受withCredentials规则限制,同时还能提升页面关闭时的上报成功率。配置代码如下:gtag('set', 'transport_type', 'beacon');方案3:通过后端代理转发上报请求
在Fiori对应的ABAP后端或BTP Destination服务中配置指向Google Analytics的代理路径,所有上报请求先发送到同域的后端接口,再由后端转发到Google服务,完全规避跨域问题。该方案同时适配企业内网无法直接访问Google服务的场景。方案4:自定义Fiori Launchpad请求规则
通过Fiori Launchpad自定义启动插件,针对Google Analytics域名的请求单独关闭withCredentials属性,避免修改全局配置影响其他业务接口的正常请求。
内容的提问来源于stack exchange,提问作者Arpita

