Back to our insights

CORS or how to be blocked during an HTTP request

3 minutes read - Technology
Share :

Have you ever encountered this kind of error when making an AJAX request to a JSON or XML file located on another domain?  

Access-Control-Allow-Origin_error

The reason could probably be related to CORS (Cross Origin Requests). In summary, the W3C has recommended this mechanism to secure HTTP requests between different domains. The recent browsers then all adopted this system which can sometimes cause some problems.  


The following article discusses this problem: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS  

Not easy to find relevant information on the Internet

The answers that can be found on the Internet are quite vague, many developers have apparently encountered this problem and many have difficulty understanding the principle. This means that we can find all kinds of answers:

  • Add a header to the AJAX request
  • Add at the beginning of its PHP file (* means all the domains, can be replaced by a domain in particular
<?php
   header('Access-Control-Allow-Origin: *');
?>

$$

  • in ASP.NET :
Response.AppendHeader("Access-Control-Allow-Origin", "*");

$$

  • Add to file HTACCESS:
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin *
</IfModule>

$$

  • Add an extension to Google Chrome.
  • Etc. 

Some of these answers are valid under certain conditions:  


For the Chrome extension (https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en) it works quite well. It allows to bypass the CORS in the browser in order to be able to test the request. Although, when the data gathered is exposed publicly, it can’t be suitable as a long terme solution since we can’t expect all visitors to have the extension installed. On the other end, permissions to add in PHP, .NET, HTACCESS involve having access to the server of the data source which could be hard to get if the data is not open and is managed by a third party (in which no one can help you to confirm the information you are missing)Also, there are no garantee that the source has been configured to accept headers.

jQuery to the rescue

Fortunately, a piece of script JQUERY is available and can help you achieve your goalsThis well hiden treasure can be found at the following link: https://github.com/padolsey-archive/jquery.fn/tree/master/cross-domain-ajaxThe only thing left to do is to add the jquery.xdomainajax.js script to your document (and of course load jQuery before) and you’re done. The script uses YQL and “simulates” a proxy to bypass security. 

References

https://code.tutsplus.com/tutorials/quick-tip-cross-domain-ajax-request-with-yql-and-jquery–net-10225

http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax

Let us be part of your transformation.

Let’s talk
This site is registered on wpml.org as a development site. Switch to a production site key to remove this banner.