Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


The whole idea behind CORS is that a browser and a foreign server need to
coordinate (by sending appropriate request and response headers) to conditionally
allow cross-domain requests. As such, a foreign server needs to be configured
properly. Browsers must be able to send appropriate requests, and headers, and
interpret server responses to successfully complete cross-domain requests.


A foreign server must be configured properly to participate in a CORS
conversation. Those who need to configure servers to accept HTTP
CORS can find more information in http://www.html5rocks.com/
en/tutorials/cors/. Here we are going to focus on the browser role
in the whole communication.

CORS requests are roughly divided into "simple" and "non-simple" ones. GET, POST,
and HEAD requests are considered as "simple" (but only when sending a subset of
allowed headers). Using other HTTP verbs or request headers outside of the allowed
set will force a browser to issue a "non-simple" CORS request.


Most of the modern browsers support CORS communication out of the
box. Internet Explorer in its Version 8 and 9 enables CORS support only
with the non-standard XDomainRequest object. Due to limitations of
the IE-specific XDomainRequest implementation AngularJS doesn't
provide support for it. As a result, the CORS requests are not supported
with the $http service on IE 8 and 9.

With non-simple requests, the browser is obliged to send a probing (preflight)
OPTION request and wait for the server's approval before issuing the primary
request. This is often confusing, since a closer inspection of the HTTP traffic reveals
mysterious OPTIONS requests. We can see those requests by trying to call the
MongoLab REST API directly from a browser. As an example, let's inspect the HTTP
communication while deleting a user:


$http.delete('https://api.mongolab.com/api/1/databases/ascrum/
collections/users/' + userId,
{
params:{
apiKey:'4fb51e55e4b02e56a67b0b66'
}
}
);
Free download pdf