I'm extremely confused by this. When I started out in web development years ago, I remember running into the SOP blocking my requests.
Yet somewhere along the way since then I forgot about it and haven't run into it in years. I know it still exists, and yet I can do $.ajax
or any other such variant without the request failing. My company's pages make dozens of requests to 3rd-party services through multiple frameworks with no issue.
What's the deal? Is it just that modern web frameworks and libraries know how to work around it, and take care of it for me? Just maybe since I haven't written out an XMLHttpRequest
by hand in years I don't run into it anymore? Is there some option to the XMLHttpRequest
, like origin
, that solves this or something?
The basic rule
Same Origin Policy applies on any HTTP call made from the page to a domain different that the webpage's domain (including sub domain) other than for a GET call.
This means that if you add a script tag to the page, load an image or perform any kind of HTTP call which uses the GET method - then you have no problem. If, on the other hand, you try to use another method, such as POST, PUT, DELETE etc., to another domain then the browser will block the call and throw an error.
Ways around this
There are, though, several ways where you can get around this.
The first is to use a GET call, but have the other side interpret the call as something else. A great example of this is a technique called JSONP, which is where we add a script tag to the page (which is a GET call) and the server responding to the GET call doesn't return just a regular JS script, but rather it returns a "uniquely tailored" response, which references the code on the originating page to tell it that it has a suitable response.
There are several patterns for achieving this, the most common is the one build into jQuery, which is where the GET call adds a query parameter with a function name, and the returned script calls that function on the global scope. jQuery listened for that call and responds accordingly. To learn more go to this answer: Confused on how a JSONP request works
The wild card
The new way around this problem, which is a much cleaner solution than JSONp is something called CORS, which is a sort of contract between the browser and the web server. Essentially what a browser will do (assuming it supports CORS, older browsers do not) is, instead of blocking a "non GET" call entirely, the browser will first perform an OPTIONS call to the web server. The webserver will take a look at the request and decide what "options" (AKA methods) this client has for communicating with it. The default is, obviously, only one option: a GET call, but you can setup your webserver to support other options such as PUT, DELETE etc. To learn more about CORS look at https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS