Hi everyone,
I’ve been struggling with CORS errors. I am trying to download image files from their URLs (served by an S3 based CDN). However, when I try to do so, I get the following error:
Access to fetch at ‘[my-cdn.com]/jpeg_ads/e360eef1-55e0-4218-ab6c-7adf6d5ce9fb.jpeg’ from origin ‘[my 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.
Here is my code:
const download = url => {
return fetch(url).then(resp => resp.blob());
};
// Function to download files in groups with controlled concurrency
const downloadByGroup = (urls, files_per_group = 5) => {
return Promise.map(
urls,
async url => {
return await download(url);
},
{ concurrency: files_per_group }
);
};
// Function to export blobs as a zip file
const exportZip = blobs => {
const zip = new JSZip();
blobs.forEach((blob, i) => {
// Adjust the file extension as needed
zip.file(`file-${i}`, blob);
});
zip.generateAsync({ type: 'blob' }).then(zipFile => {
const currentDate = new Date().getTime();
const fileName = `combined-${currentDate}.zip`;
saveAs(zipFile, fileName);
});
};
// Function to download and zip files
const downloadAndZip = urls => {
return downloadByGroup(urls, 5).then(exportZip);
};
const urls = variables['6a3bc16a-dbd1-46f4-ab2c-e55bd1530c62'].map(item => item._source.preview_url);
downloadAndZip(urls);
It uses the bluebird, jszip, and filesaver libraries which are imported inside script tags. The import seems to work because I get no import related errors.
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.7.2/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
The server is set to allow all origins, so that shouldn’t be the problem. Based on this article, I was thinking that maybe my request isn’t sending an Origin header, but I believe the browser should automatically do that.
I’ve also tried just sending a very basic fetch request for one image (no libraries), but that fails with the same error.
The images display without issue in img tags.
Any ideas? Thanks!!