What is CORS?
5 June 2022
●
2 min read
Cross-Origin Resource Sharing (CORS) is a protocol that permits servers to receive requests from different origins (domains). It bypasses the same-origin policy without decreasing security.
The same-origin policy is used by web browsers to stop malicious websites from accessing data on other sites without authorization. Two origins are the same when their protocol, port, and host are the same. However, Internet Explorer does not include ports in the same-origin control.
When a client (e.g., browser) requests files from a server, the browser will prevent access to those files unless the correct CORS headers are set. The primary header being Access-Control-Allow-Origin.
By default, a browser will not accept any asset loaded from another domain (origin) if there is no Access-Control-Allow-Origin response header present. Servers can list the domains allowed to access resources on said server, or they can return a wildcard (*) selector to allow any domain to access the resources.
If you come across this problem while building your frontend applications and you do not have access to the server, or you are making requests to third-party APIs that are not CORS enabled, the following solutions could be helpful:
One fix but not a long-term solution and should only be used for developing, debugging, and testing, is to install the Moesif CORS extension that allows you to send cross domain requests. The extension is available for Chrome and Firefox.
Another solution is to use a CORS proxy server. The same-origin policy only comes into play on a browser so using a CORS proxy server is a better solution, but just like the Moesif CORS extension, the free proxy solutions should not be relied upon and must not be used in production, so it is best to create your own. Two well known free CORS proxy servers are crossorigin.me and cors-anywhere.
CORS gives web services the control to interconnect with other web services without making their users open to attack. There is a lot more to CORS than what is mentioned above but I hope this run-down has given a you a little more understanding about CORS and how to implement a solution in your next frontend project.