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

S3 Bucket配置允许localhost与127.0.0.1,但后者CORS请求失败

问题描述

配置S3 Bucket的CORS策略,允许http://localhost:8080和http://127.0.0.1:8080的跨域请求,编写的fetch请求代码如下:

const response = await fetch('<url-replaced>', {
    method: 'GET',
    mode: 'cors'
});
const data = await response.json();
console.log(data);

在http://localhost:8080上运行正常,但在http://127.0.0.1:8080上运行时出现CORS错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://<domain replaced>/data/snap.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

查看响应头发现,127.0.0.1的请求未返回access-control-allow-origin头,而localhost的请求正常返回。当前S3 CORS配置如下:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "HEAD"
        ],
        "AllowedOrigins": [
            "http://localhost:8080",
            "http://127.0.0.1:8080"
        ],
        "ExposeHeaders": [
            "x-amz-server-side-encryption",
            "x-amz-request-id",
            "x-amz-id-2"
        ],
        "MaxAgeSeconds": 3000
    }
]
解决方案

1. 等待S3 CORS配置生效

S3的CORS配置修改后,可能需要1-5分钟才能全局生效,刚修改完就测试可能会遇到旧配置的缓存问题。可以等待一段时间后再用127.0.0.1:8080测试。

2. 清除浏览器缓存或使用隐私模式

浏览器可能缓存了之前的CORS响应头,导致新配置不生效。可以:

  • 按Ctrl+Shift+R(Windows/Linux)或Cmd+Shift+R(Mac)强制刷新页面
  • 打开浏览器隐私/无痕窗口,重新加载http://127.0.0.1:8080的页面进行测试

3. 检查请求的Origin头是否匹配

打开浏览器开发者工具(F12),切换到「Network」标签,找到对应的fetch请求,查看Request Headers中的Origin字段,确认是否为http://127.0.0.1:8080:

  • 如果Origin是其他值(比如http://[::1]:8080,即IPv6的本地地址),需要把对应地址添加到S3的AllowedOrigins列表中
  • 如果Origin格式和配置中的完全一致,继续下一步

4. 拆分CORS规则为独立条目

将原来的单条CORS规则拆分为两个独立规则,分别对应两个源,避免合并规则可能出现的匹配异常:

[
    {
        "AllowedHeaders": ["*"],
        "AllowedMethods": ["GET", "HEAD"],
        "AllowedOrigins": ["http://localhost:8080"],
        "ExposeHeaders": ["x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2"],
        "MaxAgeSeconds": 3000
    },
    {
        "AllowedHeaders": ["*"],
        "AllowedMethods": ["GET", "HEAD"],
        "AllowedOrigins": ["http://127.0.0.1:8080"],
        "ExposeHeaders": ["x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2"],
        "MaxAgeSeconds": 3000
    }
]

保存配置后等待生效,再测试127.0.0.1:8080的请求。

5. 检查S3 Bucket的静态网站托管配置(如果启用)

如果Bucket开启了静态网站托管,确保没有额外的自定义响应头覆盖了CORS配置,或者托管配置中的跨域设置和CORS规则冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:27:23