简体   繁体   English

从在一台机器上工作的浏览器下载 S3 图像并在另一台机器上出现 CORS 错误

[英]Downloading S3 image from browser working on one machine and giving CORS error on another machine

I have an Angular2 app and I am trying to download a set of images from S3 and put them in a zip file.我有一个 Angular2 应用程序,我正在尝试从 S3 下载一组图像并将它们放入一个 zip 文件中。 I am using the following code which I got from https://gist.github.com/noelvo/4502eea719f83270c8e9我正在使用从https://gist.github.com/noelvo/4502eea719f83270c8e9获得的以下代码

dlImages(urlList, jobName) {

    var zip = new JSZip();
    var count = 0;
    var zipFilename = jobName.split(" ").join("_") + ".zip";
    var img = zip.folder("images");

    console.log(zipFilename);

    urlList.forEach(function (url, idx) {
        //filename and file type should be the same it is in s3
        var fileExtension = url.split('.').pop(-1);
        var realIdx = idx + 1;
        var filename = realIdx.toString().concat(".").concat(fileExtension);
        console.log(url);
        console.log(filename);

        JSZipUtils.getBinaryContent(url, function (err, data) {
            if (err) {
                throw err; // or handle the error
            }
            img.file(filename, data, {binary: true});
            count++;

            if (count == urlList.length) {
                zip.generateAsync({type: 'blob'}).then(function (content) {
                    FileSaver.saveAs(content, zipFilename);
                });
            }
        });
    });
}

The code is running on a Heroku app and the strange thing is that it works as intended on my development machine (chrome Version 68.0.3440.106) however it gives a CORS error on another machine (chrome Version 69.0.3497.100).该代码在 Heroku 应用程序上运行,奇怪的是它在我的开发机器(chrome 版本 68.0.3440.106)上按预期工作,但是在另一台机器(chrome 版本 69.0.3497.100)上出现 CORS 错误。 The specific CORS error is具体的 CORS 错误是

Failed to load url.for.image.in.s3.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource.  Origin 'https://myherokuapp.herokuapp.com' is therefore not allowed access.

The above error is thrown for every image url in the set.为集合中的每个图像 url 抛出上述错误。 And my CORS policy for the bucket is我对存储桶的 CORS 政策是

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

Also, in my app.js file I have另外,在我的 app.js 文件中,我有

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
    next();
});

Does anyone know why this CORS error is happening for this CORS policy?有谁知道为什么这个 CORS 政策会发生这个 CORS 错误? A follow-up question is why would this work on one machine but not the other?一个后续问题是为什么这可以在一台机器上运行而不是在另一台机器上运行?

EDIT:编辑:

Below are screenshots of the response headers for each of the machines when an image is attempted to be downloaded.以下是尝试下载图像时每台机器的响应标头的屏幕截图。

This is the response header for the machine that DOES work这是工作的机器的响应头在此处输入图片说明

And here is the response header for the machine that DOES NOT work这是不工作的机器的响应头

在此处输入图片说明

So clearly the difference is that the response header for the machine that doesn't work does not have the ACCESS-CONTROL-ALLOW fields, but I don't know why that is happening.很明显,不同之处在于无法工作的机器的响应标头没有 ACCESS-CONTROL-ALLOW 字段,但我不知道为什么会发生这种情况。 I'll do some research but if anyone knows that would be very helpful.我会做一些研究,但如果有人知道那会非常有帮助。

SECOND EDIT:第二次编辑:

Also here is the request header for the machine that does not work另外这里是无法工作的机器的请求标头

Origin: https://xxxxx.herokuapp.com

Referer: https://xxxxx.herokuapp.com/yyyyyyyy/5ac2635557c3f70014529d4d

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36

The request header for the machine that does work is the same except for the user-agent.除了用户代理之外,工作机器的请求头是相同的。

Try replacing尝试更换

<AllowedOrigin>https://*</AllowedOrigin>
<AllowedOrigin>http://*</AllowedOrigin>

with

<AllowedOrigin>*</AllowedOrigin>

CORS error removed by adding CORS configuration to my bucket but still not able to download the image.通过将 CORS 配置添加到我的存储桶中删除了 CORS 错误,但仍然无法下载图像。

I tried different solutions but these are the steps that worked for me.我尝试了不同的解决方案,但这些是对我有用的步骤。 You should try these steps.您应该尝试这些步骤。

1. Add CORS configuration on your bucket. 1.在您的存储桶上添加 CORS 配置。

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

2. Add crossorigin="anynymous" to img tag 2.在img标签中添加crossorigin="anynymous"

<img crossorigin="anonymous" id="media_img" src="example.jpeg">

3. JS code 3. JS代码

  $('#media_img').on('click', () => {
    downloadImage();
  })
 
  function toDataURL(url) {
    return fetch(url).then((response) => {
      return response.blob();
    }).then(blob => {
      return URL.createObjectURL(blob);
    });
  }

  async function downloadImage() {
    const a = document.createElement('a');
    a.href = await toDataURL($('#media_img').attr('src'));
    a.download = 'example.jpeg';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以角度 6 下载 S3 图像中的 CORS 错误 - CORS error in S3 image download in angular 6 实际上将文件从 S3 存储桶下载到本地机器 - Actually Download File from S3 bucket to local machine 无法从另一台机器上的浏览器访问 angular 服务器 - Can't access angular server from a browser on another machine 从 s3 获取 object 时发生 Cors 错误 - Cors error occurs while getting object from s3 CORS 关于在 Azure 虚拟机之外的浏览器上访问 Web 应用程序的问题 - CORS ISSUES on Accessing Web Application on a Browser Outside Azure Virtual Machine 在chrome浏览器上工作的http url,但是从angular 2给出了CORS错误 - http url working on chrome browser but gives CORS error from angular 2 Angular Service Worker ngsw-config.json S3/Cloudflare 图像缓存 CORS 错误 - Angular Service Worker ngsw-config.json S3/Cloudflare Image Caching CORS Error 在 Angular 8 中的 jsPDF 中添加来自另一个域的图像的 CORS 错误 - CORS error for adding image from another domain in jsPDF in Angular 8 错误:找不到“ AppModule”的NgModule元数据。 在另一台机器上 - Error: No NgModule metadata found for 'AppModule'. on another machine 从 Amazon S3 下载图像:前端或后端 - Downloading images from Amazon S3: Frontend or Backend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM