With Google Chrome or Firefox, if I try to load the following HTML:
<script crossorigin='anonymous' src='https://stackoverflow.com/foo.js'></script>
I get a CORS error like this:
Access to Script at 'https://stackoverflow.com/foo.js' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource...
However, the same tag without the crossorigin='anonymous'
attribute works fine (of course generating a 404 error, since foo.js does not exist).
This is surprising, since anonymous
is just supposed to prevent sending any credentials, and script tags are not supposed to require CORS. What is causing this, and what should I do?
Attribute Values Specifies the mode of the CORS request: anonymous - A cross-origin request is performed. No credentials are sent. use-credentials - A cross-origin request is performed. Credentials are sent (e.g. a cookie, a certificate, a HTTP Basic authentication)
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.
In order to fix CORS, you need to make sure that the API is sending proper headers (Access-Control-Allow-*). That's why it's not something you can fix in the UI, and that's why it only causes an issue in the browser and not via curl: because it's the browser that checks and eventually blocks the calls.
The HTML crossorigin Attribute in <link> element is used to specifying that supports the HTTP CORS request when fetching or loading the stylesheet or icon files from the third-party server. Syntax: <link crossorigin="anonymous | use-credentials"> Attribute Values: anonymous: It has a default value.
I was confused about this for a while. Here's how I now understand it:
According to the W3C, there are actually three possible values for the crossorigin
attribute: anonymous
, use-credentials
, and an "missing value default" that can only be accessed by omitting the attribute. (An empty string, on the other hand, maps to anonymous
.) The default value causes the browser to skip CORS entirely, which is the normal behavior I was expecting.
The crossorigin
attribute should only be used if we care about getting error information for the script being loaded. Since accessing this information requires a CORS check, the Access-Control-Allow-Origin
header must be present on the resource for it to be loaded.
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