What is the issue CORS is trying to solve?

The default behavior of web browsers that initiate requests from a page via JavaScript (AKA AJAX) is that they follow the same-origin policy. This means that requests can only be made via AJAX to the same domain (or sub domain). Requests to an entirely different domain will fail.

This restriction exists because requests made at other domains by your browser would carry along your cookies which often means you’d be logged in to the other site. So, without same-origin, any site could host JavaScript that called logout on stackoverflow.com for example, and it would log you out. Now imagine the complications when we talk about social networks, banking sites, etc.

So, all browsers simply restrict script-based network calls to their own domain to make it simple and safe.

Site X at www.x.com cannot make AJAX requests to site Y at www.y.com, only to *.x.com

There are some known work-arounds in place (such as JSONP which doesn’t include cookies in the request), but these are not a permanent solution.

CORS allows these cross-domain requests to happen, but only when each side opts into CORS support.

Leave a Comment