CORS - Cross-origin resource sharing
CORS is a mechanism that use additional HTTP headers to tell browser to give web application running at one origin access to selected resources from a different origin.
Same-origin policy prevents JavaScript from making requests across domain boundaries. Two URLs have the same origin if the protocol, port and host are the same for both
A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (protocol, post or host) from its own.
Preflight request
For HTTP request methods than can cause side effects on server data, CORS
specification mandates that browser make “preflight” request. Preflight request
is made with HTTP OPTIONS
request method and upon approval from server
send the actual request.
Simple requests
Simple requests are GET
or POST
with no custom headers and whose
body is text/plain
, the request is sent with an extra header ORIGIN
.
The ORIGIN
header contains origin (protocol, post or host) of the requesting
page. If the server decides to allow the request it sends a Access-Control-Alow-Origin
header sending back same origin or *
if its a public resource.
Request with credentials
By default cross domain requests will not send credentials (cookies etc.).
With property withCredentials
set to true
on XMLHTTPRequest
,
the credentials can be sent in the request. But the browser will
reject the response if response doesn’t have Access-Control-Allow-Credentials: true
.