[XMLHttpRequest] Cross-domain Ajax REST request + No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Context :

In summary, this article is to record the solution for an “No ‘Access-Control-Allow-Origin’ header is present on the requested ressource” error.

My local domain is : localhost, in which based my local application

My request domain is : http://www.example.com, which is write in PHP, and will return a simple object in JSON
Such as : {"return":"OK"}


The source code in Javascript that I used :

$.ajax({
 type: "GET",
 dataType: 'JSON',
 url: "www.example.com",
 success : function() {
    // Do something
 },
 error : function() {
   // Do something else
 }
})

Error :

XMLHttpRequest cannot load http://www.example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

Reason:

The mainly reason is security.
According to Wikipedia Cross-Domain: In the early development of the World Wide Web, it was found possible to breach users’ security by the use of JavaScript to exchange information from one web site with that from another less reputable one. All modern browsers therefore implement a same origin policy that prevents many such attacks, such as cross-site scripting. XMLHttpRequest data is subject to this security policy, but sometimes web developers want to intentionally circumvent its restrictions. This is sometimes due to the legitimate use of subdomains as, for example, making an XMLHttpRequest from a page created by foo.example.com for information from bar.example.com will normally fail.

N.B. To be noticed here is, example.com and http://www.example.com are not the same domain.

Solution :

Of course, you need to have the control of your destination, the back office. For me, it is the http://www.example.com domain.

At the beginning of my PHP script, I added the header which allows all origin requests :

<?php
  header('Access-Control-Allow-Origin: *');

After that, it works for me, so if this article can help, it’s my pleasure 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s