Axios CORS 无法在 chrome 部署的站点上工作

Car*_*rel 1 amazon-s3 cors axios

我在 VueJS 应用程序中有以下方法:

const downloadImageBase64 = async imageUrl => {
  try {
    var result = await axios({
      method: "get",
      url: imageUrl,
      responseType: 'blob',
      crossdomain: true
    });

    return blobToBase64(result.data);
  }
  catch (err) {
    console.log("err: ", err);
    return "";
  }
};
Run Code Online (Sandbox Code Playgroud)

我正在下载图像并将它们作为 base64 字符串返回,因为我将它们嵌入到使用 JSPDF 创建的 PDF 中。图像本身托管在 AWS S3 中。我在适当的 S3 存储桶中设置了 CORS 策略:

[
  {
    "AllowedHeaders": [
      "*"
    ],
    "AllowedMethods": [
      "GET"
    ],
    "AllowedOrigins": [
      "https://mydomain.co.za"
      "http://localhost:8082"
    ],
    "ExposeHeaders": [],
    "MaxAgeSeconds": 3000
  }
]
Run Code Online (Sandbox Code Playgroud)

在我的本地主机上运行应用程序时,FireFox 和 Chrome 均可成功下载图像:

在此输入图像描述

然而,当我将应用程序部署到临时环境时,下载开始失败,并出现 CORS 问题,但仅限于 Chrome。查看请求标头,甚至没有发送 CORS 信息:

在此输入图像描述

我不知道 Chrome 是否在网络流量中未显示预检,但控制台给出了以下错误:

从源“https://mydomain.co.za”访问“https://my-bucket.s3-eu-west-1.amazonaws.com/my-image-path.png”处的 XMLHttpRequest 已被阻止CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头。

Car*_*rel 5

事实证明,问题是我在放置下载 PDF 按钮的网页上显示图像,这意味着 chrome 缓存了这些图像,并且当尝试下载 PDF 图像时,chrome 会返回没有 CORS 标头的缓存图像。我或多或少从这里得到了答案:

https://www.hacksoft.io/blog/handle-images-cors-error-in-chrome

因此,解决方案是在下载 PDF 时在 URL 中附加一个一次性的 get 参数:

const downloadImageBase64 = async imageUrl => {
  try {
    var result = await axios({
      method: "get",
      url: `${imageUrl}?not-from-cache-please`,
      responseType: 'blob',
      crossdomain: true
    });

    return blobToBase64(result.data);
  }
  catch (err) {
    console.log("err: ", err);
    return "";
  }
};
Run Code Online (Sandbox Code Playgroud)

请注意:

url: `${imageUrl}?not-from-cache-please`
Run Code Online (Sandbox Code Playgroud)