Friday, March 29, 2013

HTTP access control (CORS)

Sometimes if we used XMLHttpRequest in javascript it gives us error:

Origin http://examplehost:80/ is not allowed by Access-Control-Allow-Origin.

This error means that the server side don't allow the requests from different domain so in this example if the server side is working also in http://examplehost:80 it will be working without problems.
so how we can solve this problem?!

Firstly we need to know what is The Cross-Origin Resource Sharing standard ...
It works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser.  Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request header, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.  Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.

we can use  Cross-Origin Resource Sharing standard by adding
 Access-Control-Allow-Origin: <origin> | *  <origin> is a specific domain name.
in the response header so this mean that the server will accept the XMLHttpRequest of this domain or * which means any domain.
they are many options in Cross-Origin we can know it from

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Regards,

No comments:

Post a Comment