如何绕过跨源策略 [英] How to bypass Cross origin policy

查看:61
本文介绍了如何绕过跨源策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要访问另一台服务器中的 JSON 文件的移动应用程序.并且其显示的跨源策略被阻止.那么有没有办法绕过或访问该文件?

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 ?

推荐答案

正如已经回答的那样,您需要一个简单的 php 代理脚本.

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

通过这种方式,您的服务器获取 json 文件,您只需从客户端访问您的服务器..这样 javascript 只处理同一个域.

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']);
?>

另一种方法是将所有请求标头作为查询字符串发送,这也可以是 post/get

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;
}

?>

使用第二个示例,您可以尝试类似 http://localhost/proxy.php?file=somefile.json

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

HTACCESS 方法

关于在服务器上使用 htaccess 文件,请参考以下页面 htaccess Access-Control-Allow-起源

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>

这篇关于如何绕过跨源策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆