DZone

What is CORS

Cross-Origin Resource Sharing (CORS) is a security mechanism built-in most modern browsers to restrict accessing resources from a server hosted on a different domain. Using CORS techniques, servers can limit the sharing of data to only trusted domains. Assume you have a frontend website hosted on https://www.contoso.com. Some JavaScript code from your website is trying to access an API hosted on https://www.foobar.com. This is an example of Cross-Origin Resource Sharing because the requesting domain and the resource domain are different. https://www.foorbar.com might have some sensitive information that it can share with only specific trusted domains, then https://www.foobar.com can specify a CORS policy where it can block requests from other domains than the trusted sites. If the request originates from the same domain, then CORS doesn’t come into play.

How CORS Works

When JavaScript from the frontend initiates an AJAX call, the browser will need to check if Server has enabled CORS. In such a situation instead of sending the actual request, the browser will make a ‘preflight’ request to the server to determine if the server has enabled resource sharing with the current domain. The browser makes a preflight call by sending an HTTP request with the OPTIONS method to the origin containing the resource. The HTTP options call will also send the current origin, non-standard headers, and the original HTTP call method.

Source: DZone