Gist:
I have a page that uses tag loading of an image from s3 (HTML img
tag) and I have a page that uses xmlhttprequest
. The tag loading gets cached without the CORS headers and so the xmlhttprequest
sees the cached version, checks it's headers and fails with a cross origin error.
Details:
edit: Fails in both safari 5.1.6 and chrome 21.0.1180.89. Works fine in Firefox 14.
Using S3's new CORS, I setup a CORSRule
as so:
<CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <MaxAgeSeconds>0</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule>
If I request an image from S3 without setting the origin in the request headers I get back the image without any CORS headers in the response.
This get's cached and subsequent CORS requests (one's that do set the origin in the request header) get rejected as the browser uses the non CORS version form the cache.
What's the best way to solve this? Can I set something so the non CORS version never gets cached? Should I differentiate the CORS requests by appending a ?some_flag
to the url of the request?
Ideally I'd have S3 ALWAYS send back the needed CORS headers even if the request doesn't contain "origin".
Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.
Open a network tab in your console. In the response header look for the Access-Control-Allow-Origin header. If it does not exist then add it as a middleware in the way we discussed above. If it does exist then make sure there is no URL mismatch with the website.
< access-control-allow-origin: * You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it! Thanks this helps to avoid all the hassle and test the code from localhost.
I ran into the same problem. As @monsur said, the problem is that S3 doesn't set teh "Vary: Origin" header, even though it should. Unfortunately, as far as I know there is no way to get S3 to send that header. However, you can work around this by adding a query string paramater to the request such as ?origin=example.com
when you need CORS. The query string forces the browser not to use the cached resource.
Ideally, cloudfront and S3 would send the Vary:Origin header when CORS is enabled and/or Webkit would implicitly vary on the Origin header, which I assume Firefox does since it doesn't have this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With