I am configuring a simple javascript fetch of a resource on S3 bucket which is delivered by Cloudfront. This is not working not only for localhost but for any other origins, see the response of AWS:
Response: Access to image at from origin 'http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
After chatting with AWS support, everything was configurated in the correct way: CORS in S3 bucket, header request in cloudfront distribution, including the following in the "Cache Based on Selected Request Headers" - Headers Whitelist.
- Origin
- Access-control-allow-methods
- Access-control-allow-headers
Cloudfront seems to do not provide Access-Control-Allow-Origin headers. Have anybody solved the issue of simple fetching from S3 via cloudfront?
These are response headers:
accept-ranges: bytes
content-length: 100286
content-type: image/jpg
date: Mon, 05 Oct 2020 18:36:18 GMT
etag: "81e0932668804433487c4ab834e8a017"
last-modified: Fri, 08 May 2020 01:55:46 GMT
server: AmazonS3
status: 200
via: 1.1 4ba9d3779ca8afc198240a34dffb07c4.cloudfront.net (CloudFront)
x-amz-cf-id: 8YQXChq71yTXuTK8OQ4TwtHIYA2oEgqdXvWnUJiU0CHDIxwMiV2iyQ==
x-amz-cf-pop: DUS51-C1
x-amz-version-id: wceb3chundfHz43URYzzrTyIBKh7bisb
x-cache: Miss from cloudfront
This is an example of the javascript download code:
const img = new Image();
// img.crossOrigin = 'Anonymous'; // This tells the browser to request cross-origin access when trying to download the image data.
// ref: https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image#Implementing_the_save_feature
img.setAttribute('crossorigin', 'anonymous');
img.src = image.sampleUrl;
img.onload = () => {
// create Canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
// create a tag
const a = document.createElement('a');
a.download = 'preview.jpg';
a.href = canvas.toDataURL('image/jpg');
a.click();
};
};```
[1]: https://i.stack.imgur.com/f6EoF.png
[![cloudfront config][1]][1]