问题
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 ?
回答1:
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>
回答2:
Use header function. check out this link how to bypass Access-Control-Allow-Origin?
header('Access-Control-Allow-Origin: *');
回答3:
You categorized this under PHP. You would do well to get the JSON with PHP then use PHP to create the data required by the JS.
Without more information regarding your app, I am very limited here.
This is a very typical PHP example geting json data into JavaScript:
$json = json_decode(file_get_contents('http://example.com/data.jsn'),true);
$JS = 'var data = ';
foreach ($json as $key => $value){
$JS .= "[$key,$value],"
}
$JS = substr($JS,0,-1) . ';'; // remove trailing comma, add semicolon
echo <<<EOT
<script type="text/javascript">//<![CDATA[
$JS
//]]>
</script>
EOT;
来源:https://stackoverflow.com/questions/29997705/how-to-bypass-cross-origin-policy