如何修复通过 S3 存储桶从 Cloudfront 提供的应用程序的 GA4 测量协议 CORS 预检块?

问题描述 投票:0回答:1

我正在尝试将 UA 更新到 GA4。该应用程序位于 S3 存储桶中并托管在 CloudFront 上。

在 Postman 中发送分析事件对我有用,我必须将

Content-Type
设置为
application/json

但是,下面的方法不起作用。

try {
        fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
            method: "POST",
            headers: {
               "Content-Type": "application/json",
            },
            body: JSON.stringify({
                    client_id: client_id
                    events: [{
                        name: event,
                        params: params,
                    }]
                })
            });
    } catch (error) {
        console.log(error)
    }
}

错误是 405 -

Access to fetch at 'https://www.google-analytics.com/mp/collect?measurement_id=<measurement id>&api_secret=<api secret>' from origin 'https://<cloudfront id>.cloudfront.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

我尝试在 s3 存储桶中设置 CORS:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "POST",
            "GET",
            "PUT",
            "DELETE",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*.cloudfront.net"
        ],
        "ExposeHeaders": []
    }
]

我还尝试在 Google Analytics 4 仪表板的管理数据流跨域测量中设置 cloudfront url。

我知道这与不接受 application/json、仅接受 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 的简单请求有关。但是,Google Analytics 4 测量协议需要 application/json。

问题: 如何在不使用 CORS 策略块的情况下使用所需的 JSON 将 GA4 分析事件从 CloudFront/S3 发送到 GA4 测量协议 API?我必须使用代理吗?

json amazon-s3 cors http-post google-analytics-4
1个回答
0
投票

由于您无法修改 Google Analytics 服务器上的标头,因此一种常见的方法是设置代理服务器。代理服务器可以将请求转发到 Google Analytics,并向响应添加适当的 Access-Control-Allow-Origin 标头。

© www.soinside.com 2019 - 2024. All rights reserved.