What is Cross-Origin Resource Sharing (CORS)?

What is Cross-Origin Resource Sharing (CORS)?

Photo by FLY:D on Unsplash

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. -Wikipedia

CORS is an HTTP-header based mechanism that allows a server to indicate any origins other than its own from which a browser should permit loading resources-MDN

CORS, or Cross-Origin Resource Sharing, enables the transfer of resources such as JavaScript and web fonts from domains other than the origin parent domain. A web page nowadays frequently loads pictures, stylesheets, scripts, and other resources from other sites. Although, for security reasons, web fonts and AJAX (XML HTTP Requests) were formerly restricted to the same-origin policy, which limited their use across domains. However, with the usage of CORS, the browser and server can communicate to determine whether a cross-origin request is safe to authorise.

CORS enables a client to send a cross-origin request to a server. Cross-origin means obtaining information from a domain other than the one from which the request originated. Based on HTTP headers, the server from which you made a request will either accept or decline your request, indicating whether or not your origin is permitted. If the request is simple, such as a get request, then the user-agent will automatically set the headers. If the request was a preflight request, the browser will send the OPTIONS method along with it to assess whether or not the request is permitted. CORS adheres to a same-origin policy, which permits only particular sources to send any request to the server unless specific CORS headers are given.

The crossorigin property, which is usable on the audio>, image>, link>, script>, and video> elements, defines how the element handles cross-origin requests, allowing the setup of CORS requests for the element's fetched data. The attribute may be a CORS settings attribute depending on the element.

The same-origin policy is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin - MDN