DEV Community

clusterO
clusterO

Posted on

Cross-origin resource sharing (CORS)

Cross-origin resource sharing" (CORS) is a mechanism that allows resources on a web page to be requested from another domain outside the domain from which the resource originated. This is useful for AJAX applications where JavaScript running in the browser may make requests to other domains (e.g. requesting JSON data from a server) or when web pages are served by a web server other than the one that generated them (e.g. when using content delivery networks). CORS is designed to allow safe cross-domain requests, while at the same time preventing malicious cross-domain requests.

In CORS, an HTTP request is made to a server in a different domain using an HTTP method other than GET or HEAD, and includes an Origin header field in the request. The server then checks whether the origin of the request matches any of the origins allowed by the Access-Control-Allow-Origin header field in the response. If so, it returns an Access-Control-Allow-Origin header field in the response containing the origin that was matched. The browser then checks this value against its list of domains and if it matches, allows the resource to be loaded. If it does not match, the resource is blocked from loading.

The following code snippet shows how to use CORS with PHP:

<?php header('Access-Control-Allow-Origin: *'); 
   header('Access-Control-Allow-Methods: GET, POST'); 
   header('Access-Control-Allow-Headers: Content-Type'); 
   header('Access-Control-Max-Age: 86400'); 
?> 

<script type="text/javascript"> // Set up headers for CORS 
   var xhr = new XMLHttpRequest(); 
   xhr.open("GET", "https://example.com/api/v1/user", true); 
   xhr.setRequestHeader("Accept", "application/json"); 
   xhr.setRequestHeader("Content-Type", "application/json"); 
   xhr.setRequestHeader("X-Requested-With", 
      "XMLHttpRequest"); 
   xhr.onload = function() { 
      console.log(this.responseText); 
   }; 
   xhr.send(); 
</script>
Enter fullscreen mode Exit fullscreen mode

For more information about CORS, see What is Cross Origin Resource Sharing? on MDN Web Docs and Cross Origin Resource Sharing on HTML5 Rocks .

Note: In JavaScript, sending a preflight OPTIONS request to find out what origins are allowed for a given resource is not supported by all browsers

Top comments (0)