在 Chrome 和 Safari 上从 CDN (S3) 获取和下载图像时出错

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

我有一个 fetch 函数,可以从 URL (S3 CDN) 下载媒体文件。

它在 Firefox 上完美运行,但在 Chrome 和 Safari 上下载图像(例如 .png)时会导致 CORS 错误。

视频(例如 .mp4/.mov)由于某种原因似乎不受影响。

错误如下所示:

Access to fetch at '<url>.png' from origin '<domain>' has been blocked by CORS policy: 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.

该函数执行以下操作:

 const response = await fetch(mediaUrl);

  const blob = await response.blob();
  const downloadUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = this.getFileNameFromUrl(mediaUrl) || 'media';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(downloadUrl);

我非常确定,由于它处理视频文件,因此不必对 S3 CORS 配置执行某些操作,但您仍然可以在下面找到 CORS 配置:

[
 {
    "AllowedHeaders": [
        "*"
    ],
    "AllowedMethods": [
        "PUT",
        "GET"
    ],
    "AllowedOrigins": [
        "<domain>"
    ],
    "ExposeHeaders": [
        "ETag"
    ]
 }
]
javascript typescript amazon-s3 fetch-api media
1个回答
0
投票

也许有更简单的方法,但现在我们只是在获取之前对 URL 进行预签名。这消除了错误。

https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html

对于node.js: https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-s3-request-presigner/

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