【问题标题】:Getting images off of S3 with CORS issues使用 CORS 问题从 S3 获取图像
【发布时间】:2019-12-20 03:51:32
【问题描述】:

我正在尝试从 AWS S3 获取图像,但遇到了 CORS 问题。

我在 Android 上的 Cordova 应用程序中遇到错误:

SystemWebChromeClient: http://localhost:8080/#/: Line 0 : Access to image at 'https://s3.us-east-2.amazonaws.com//wantify/merchants/56/logo.png' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是由于以下代码:

  getColors(this.props.merchant.logo).then(colors => {
    var colorsHex = colors.map(color => color.hex());
    this.lightestColor(colorsHex);
  });

现在 getColors 来自库 get-image-colors,所以我的理解是它自己进行调用。

我试图弄清楚如何忽略 CORS 或遵守 S3 的 CORS。

我的 CORS 设置如下:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedOrigin>localhost:8080</AllowedOrigin>
    <AllowedOrigin>http://localhost:8080</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

get-image-colors 也允许使用 base64 缓冲区,但是当我尝试这样做时,我也没有成功。

  getBase64(this.props.merchant.logo).then(function(base64) {
    console.log("axios base64");
    console.log(base64);
  });
  function getBase64(url) {
    return axios
      .get(url, {
        responseType: "arraybuffer",
        headers: {
          Origin: "Example"
        }
      })
      .then(response => new Buffer(response.data, "binary").toString("base64"));
  }

我在这里做错了什么?如何在没有 CORS 问题的情况下获取图像?我知道 AWS 需要 Origin 标头(这使得在 Chrome 中进行测试令人头疼),但即使我包含它,就像上面的 base64 示例一样,它也不起作用。

如何正确地从 AWS S3 获取图像?

【问题讨论】:

    标签: javascript amazon-web-services amazon-s3 cors


    【解决方案1】:

    已编辑:这是一个错误答案(请参阅下面的 cmets)Amazon S3 不接受 OPTIONS 作为 CORS 操作

    Axios 很可能会在 GET 之前发出 OPTIONS 请求。请务必将 OPTIONS 操作添加到您在 Amazon S3 上的 CORS 策略中,

    例如:

    <CORSRule>
       <AllowedOrigin>http://localhost:8080</AllowedOrigin>
    
       <AllowedMethod>GET</AllowedMethod>
       <AllowedMethod>OPTIONS</AllowedMethod>
    
       <AllowedHeader>*</AllowedHeader>
     </CORSRule>
    

    为了进一步调试,我建议按照https://docs.aws.amazon.com/AmazonS3/latest/dev/cors-troubleshooting.html 中描述的步骤进行操作

    【讨论】:

    • 我的理解是 S3 不需要显式使用 OPTIONS,但我会测试一下
    • 是的,S3 不支持选项:“在 CORS 配置中发现不支持的 HTTP 方法。不支持的方法是 OPTIONS”
    • 好的,很高兴知道我的 API Gateway 配方不适用于 S3 :-) 我让您从请求和响应中捕获完整的 HTTP 标头,请将它们发布在问题中以供进一步调试跨度>
    • 但是根据文档,Aazon S3 确实支持预检请求(OPTIONS):docs.aws.amazon.com/AmazonS3/latest/API/RESTOPTIONSobject.html(但不是在 CORS 设置中,你是正确的docs.aws.amazon.com/AmazonS3/latest/dev/cors.html
    • 我上面写的错误消息是亚马逊在我尝试在允许的方法下保存 OPTIONS 时给我的确切错误消息。我相信他们隐含地支持 OPTIONS,而不是明确地支持。
    猜你喜欢
    • 2014-11-07
    • 2018-10-05
    • 2019-02-21
    • 2019-11-29
    • 2019-04-08
    • 2016-09-04
    • 2016-07-14
    • 2020-02-01
    • 2017-12-30
    相关资源
    最近更新 更多