[WEB] CORS (Cross-Origin Resource Sharing)

 CORS (Cross-Origin Resource Sharing)

Concept

CORS is a browser security mechanism restricting web pages from making JavaScript-based HTTP requests to domains other than the one serving the web page. It prevents unauthorized data access, ensuring better security and privacy.

By default, JavaScript code (using AJAX or fetch) within <script> tags cannot directly request data from other domains unless those domains explicitly permit it.

<script>
    fetch('https://www.google.com')
        .then(response => response.text())
        .then(data => console.log(data))
        .catch(error => console.error(error));
</script>

Google's servers don't explicitly allow this request since this is from an external domain.

Allowed cases

Simple HTML elements such as <img>, <script>, or <link> are permitted by browsers to load resources from external domains without triggering CORS restrictions, as they do not actively read or manipulate the retrieved data using JavaScript.

<img src="https://www.google.com/images/googlelogo.png">

This request is allowed By Google's server.

How to bypass CORS with CDN-hosted scripts (Axios or Vue)

CDNs explicitly set HTTP headers allowing cross-origin requests, such as:
Access-Control-Allow-Origin: *

This informs browsers it's safe to load the resources from these domains, bypassing CORS restrictions.

Point of CORS

Keep the requests within the same domain. If resources from other domains, retrieve them on the server-side first and serve them from my domain.

Comments