Search code examples
javascriptphpsame-origin-policy

How to bypass Cross origin policy


Mobile app where it needs to get access to a JSON file in another server. And its showing cross origin policy blocked. So is there any way to bypass or have the access to the file ?


Solution

  • As already answered, you want a simple php proxy script.

    This way your server grabs the json file and you simply access your server from client side. . That way javascript is only dealing with the same domain.

    <?php
      header('Content-Type: application/json');
      echo file_get_contents('http://example.com/data.json');
    ?>
    

    Proxy.php

    <?php
      header('Content-Type: application/json');
      echo file_get_contents('http://example.com/'.$_REQUEST['file']);
    ?>
    

    Another way also would be to send all of the request headers as a query string, this could be post/get as well

    if (isset($_REQUEST['query'])) {
        $sQuery = http_build_query($_REQUEST);
        header('Content-Type: application/json');
        echo file_get_contents('https://www.example.com?'.$sQuery);
        exit;
    }
    
    ?>
    

    Using the second example you can try something like http://localhost/proxy.php?file=somefile.json

    HTACCESS METHOD

    Refer the following page about using a htaccess file on the server htaccess Access-Control-Allow-Origin

    <FilesMatch ".(json|js|jsn)">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>