Solution usin JSON-P
Contents
If the above method is not working or you have any restriction in modifying the .htaccess or apache configuration file, then another workaround is using JSON-P (JSON-with-padding). In this method, the client expects the data returned by the API in JSON-P format. This method, for me is a dirty hack, but it should work in most of the situations.
In the client side ajax call we can have following code:
1 2 3 4 5 6 7 8 |
var domain = "http://example.com"; //this will be the domain which provides the REST API $(document).ready(function() { $.ajax({ url: domain+"/api", async:true, dataType : 'jsonp' //we are using jsonp as the data type returned }) }); |
On the server side the API will return in the JSON-P format. Below is an example in PHP:
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Here lets assume that the $values will be records returned //from the DB table foreach($values as $value) { $info[] = array( 'id' => $value->id, 'name' => utf8_encode($value->name), 'logo' => $value->logo_uri, ); } echo 'json_processor('. json_encode($teams_info). ');'; |
You might have noticed json_processor in the echo statement. This is the javascript callback function which is returned along with the json encoded array. The returned json value to the browser will be similar to the one below:
1 2 3 4 |
json_processor([{"id":1,"name":"FC Barcelona","logo":"https:\/\/upload.wikimedia.org\/wikipedia\/en\ /thumb\/4\/47\/FC_Barcelona_%28crest%29.svg\/1010px-FC_Barcelona_%28crest%29.svg.png"},{"id":2,"name" :"Manchester United F.C.","logo":"http:\/\/www.manutd.com\/~\/media\/510AE241278B45FF97125DC1E1E32CBF .ashx"}]); |
Now in our client side, we need to define the callback javascript function json_processor(). This function will be called automatically once the browser gets the API response.
1 2 3 4 |
function json_processor(data){ //data will be the json values from the API console.log(data); } |
NOTE: The method of using JSON-P is not a workaround to access REST API of any websites for which you don’t have any control of. This implementation requires code modification on both client as well as server side. This method should be considered only if the CORS headers is not working.
You can also check the open source program [Bypass Cors](https://chrishham.github.io/BypassCors/) ,
an installable Electron App (Windows/Mac/Linux), that lets you Bypass ALL CORS Restrictions permanently,
by allowing you to set your own custom Headers (+Origin).
It is specifically designed to work with Web Apps and its perfect for Real Time Scraping.
Disclaimer: I am the author of the program.
Thanks, Christopher, your project looks interesting. Will give it a try