Search code examples
reactjsamazon-s3amazon-cloudfront

I am receiving an error while downloading the image from an S3 bucket


S3 bucket CORS configuration:

        [
            {
                "AllowedHeaders": [
                    "*"
                ],
                "AllowedMethods": [
                    "GET",
                    "HEAD",
                    "PUT",
                    "POST",
                    "DELETE"
                ],
                "AllowedOrigins": [
                    "*",
                    "https://performance.mobilads.co"
                ],
                "ExposeHeaders": [
                    "x-amz-server-side-encryption",
                    "x-amz-request-id",
                    "x-amz-id-2",
                    "ETag"
                ],
                "MaxAgeSeconds": 3000
            }
        ]

My Download image code:

        downloadImages = (s3Url) => {
            const urlParts = s3Url.split('/');
            const imageName = urlParts[urlParts.length - 1];
            fetch(s3Url, {
              method: 'GET'
            })
              .then(res => {
                if (!res.ok) {
                  throw new Error(`Failed to fetch: ${res.status} ${res.statusText}`);
                }
                return res.blob();
              })
              .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = imageName;
                document.body.appendChild(a);
                a.click();
                setTimeout(
                  _ => { window.URL.revokeObjectURL(url); },
                  60000);
                a.remove();
              })
              .catch(err => {
                console.error('Error fetching image: ', err);
              });
          }

Error:

Access to fetch at 'https://mobilads-maps-hosting.s3.amazonaws.com/public/prod/campaign-shoots/204/ll9mqhj3-1066461b5705cbd2a4a074dfa7df12e9.jpg' from origin 'http://localhost:3001' 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. network-breadcrumbs.js:134 GET https://mobilads-maps-hosting.s3.amazonaws.com/public/prod/campaign-shoots/204/ll9mqhj3-1066461b5705cbd2a4a074dfa7df12e9.jpg net::ERR_FAILED

I tried changing the CORS policy to specific website url and development url in Allowed origin. still does not work.


Solution

  • you have to set mode as 'no-cors' to request