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

0

S3 bucket CORS configuration:

    [
        {
            "AllowedHeaders": [
                "*"
            ],
            "AllowedMethods": [
                "GET",
                "HEAD",
                "PUT",
                "POST",
                "DELETE"
            ],
            "AllowedOrigins": [
                "*"
            ],
            "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.

asked 10 months ago816 views
1 Answer
0

Hi,

are you by any chance using Chrome to test it? Chrome does not support localhost for CORS requests, see this Stack Overflow post

profile pictureAWS
EXPERT
answered 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions