Search code examples
javascriptamazon-s3corsfetch

Download file from AWS S3 using fetch method throws CORS error


I added below s3 config to my AWS S3 bucket cors setting.

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "https://*.herokuapp.com"
        ],
        "ExposeHeaders": []
    },
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

Now when I am trying to read it using below JS, I am getting error.

async function covertToBlob(url) {
  // https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html
  const resp = await fetch(url, {
    credentials: 'include',
  });
  const blobVal = await resp.blob();
  return blobVal;
}

Error is:

Access to fetch at 'https://dhdhddh.s3.amazonaws.com/docs/attachment/6f56abfe-a355-44b9-b728-a642f661a8e7/file/3ed4e889-e139-4755-81e9-5383310e07e7/remote_sounding_system_Hanla.pdf' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

Would you give me some ideas about how can I fix this?


Solution

  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#sending_a_request_with_credentials_included

    Note: Access-Control-Allow-Origin is prohibited from using a wildcard for requests with credentials: 'include'. In such cases, the exact origin must be provided; even if you are using a CORS unblocker extension, the requests will still fail.

    That means, the value for AllowedOrigins must not contain any wildcard character. You must specify the exact origin.

    This is per the Fetch API specification.