What is the issue CORS is trying to solve?

CodyBugstein picture CodyBugstein · Dec 8, 2014 · Viewed 7.7k times · Source

I've been reading up on CORS and how it works, but I'm finding a lot of things confusing. For example, there are lots of details about things like

User Joe is using browser BrowserX to get data from site.com, which in turn sends a request to spot.com. To allow this, spot has special headers... yada yada yada

Without much background, I don't understand why websites wouldn't let requests from some places. I mean, they exist to serve responses to requests, don't they? Why would certain people's of requests not be allowed?

It would really appreciate a nice explanation (or a link to one) of the problem that CORS is made to solve.

So the question is,

What is the problem CORS is solving?

Answer

Haney picture Haney · Dec 8, 2014

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.