同源策略、跨域、jsonp

问答

1.什么是同源策略

  • 同源:


    URL组成

URL由协议、域名、端口和文件路径组成,而如果两个URL的协议、域名和端口均相同,则表示它们是同源

  • 同源策略:
    不同源的客户端脚本在没明确授权的情况下,不能读写对方的资源。这就是同源策略,它是浏览器为了安全性考虑一种非常重要的策略。
    例如:a.com/index.html可以引用
  • b.com/main.js
  • b.com/style.css
  • b.com/logo.png
    但是被a.com引用之后的b.com/main.js就不能对b.com的资源进行读写(ajax报错)

2.什么是跨域?跨域有几种实现形式?

  • 跨域:
    出于同源政策,不同源的客户端脚本是不能读写对方的资源,而跨域就是采取某些技术突破这个限制。

  • 跨域的几种形式:

(1)降域:
对于主域相同而子域不同的网址,可以使用降域的方法,也就是设置document.domain。配合iframe标签使用达到2个js文件之前的“交互”。
缺点是:无法使用ajax,只能在主域相同的情况下使用,有安全性问题。
(2)JSONP:
通过创建script节点的方法来实现跨域,兼容性好,支持老版本的浏览器。
缺点是:只能发送GET请求,无法判断请求是否失败,也有安全性问题,可以通过前后端约定一个token变量来验证。
(3)CORS:
一个W3C标准,允许浏览器跨域请求资源。
缺点是:有兼容性问题,IE浏览器不能低于IE10。

CORS兼容

(4)hash:可以利用location.hash值来传递数据。
缺点是:数据容量有限。
(5)window.name:只要tab页面不会关闭,name值在不同的域名加载后依旧存在,利用这一原理可以实现跨域。

3.jsonp的原理是什么?

<script>标签的scr属性并不被同源策略所影响,它可以获取任何服务器上的脚本并加载。
jsonp的原理就是动态的创建一个<script>标签,利用<script>标签跨域的能力获取服务器上的脚本。事先在本地文档中创建回调函数,然后在服务器的上调用这个函数并且将JSON数据作为参数传递,最后完成回调。

4.CORS是什么?

CORS是一个W3C标准,全称是“跨域资源共享”,使用它可以实现浏览器上跨院服务器发出XMLHTTPRequest请求,从而克服了ajax只能同源使用的限制。
CORS需要浏览器和服务器同时支持,目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。

练习

1.本地搭建服务器,演示同源策略

1. 本地搭建服务器(如果使用 SAE 可创建不同的代码版本,这样可通过1.xxx.sinapp.com和2.xxx.sinapp.com 访问了)
2. 修改 本地host,通过不同域名访问本地服务器。比如访问http://a.com/index.html, http://b.com/ajax.php,本质是在 index.html 里使用 ajax 接口访问 http://b.com/ajax.php 里的数据。
3. 查看输出报错

使用WAMP在本地创建多个站点:

创建域名
修改本地HOST
访问test01.com
访问test02.com

在test01.com中创建一个test01.html,通过ajax来访问test02.com下的test02.php。

test01.html代码如下:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>同源政策测试</title>
</head>
<body>
<input id="btn" type="button" value="读取后台信息"/>
<script>
    function ajax(opts){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
                var json = JSON.parse(xmlhttp.responseText);
                opts.success(json);
            }
            if(xmlhttp.readyState === 4 && xmlhttp.status === 404){
                opts.error();
            }
        };
        var dataStr = "";
        for (var key in opts.data) {
            dataStr += key +'='+ opts.data[key]+ '&';
        }
        dataStr = dataStr.substr(0,dataStr.length-1);

        if(opts.type.toLowerCase() === "get"){
            xmlhttp.open("GET",opts.url+"?"+dataStr,true);
            xmlhttp.send();
        }
        if(opts.type.toLowerCase() === "post"){
            xmlhttp.open("POST",opts.url,true);
            xmlhttp.setRequestHeader("Contenr-type","application/x-www-form-urlencoded");
            xmlhttp.send(dataStr);
        }
    };

    document.querySelector('#btn').addEventListener('click', function(){
        ajax({
            url: 'http://test02.com/test02.php',
            type: 'get',
            data: {
                username: 'xiaoming',
                password: 'abcd1234'
            },
            success: function(res){
                onSuccess(res);
            },
            error: function(){
                console.log('出错了')
            }
        })
    });

    function onSuccess(json){
        console.log(json)
    };
</script>
</body>
</html>

test02.php代码如下:


<?php 
    $username = $_GET['username'];
    $password = $_GET['password'];
    $person = "你的用户名是:".$username." "."你的密码是:".$password;
    echo json_encode($person);
 ?>

测试结果就是同源政策的限制:

运行结果

2.至少使用一种方式解决跨域问题

(1):使CORS方法:
test01.html无需修改,只要在test02.php里面添加header('Access-Control-Allow-Origin: http://test01.com')即可。
php代码:

<?php 
header('Access-Control-Allow-Origin: http://test01.com');
    $username = $_GET['username'];
    $password = $_GET['password'];
    $person = "你的用户名是:xiaoming"." "."你的密码是:abcd1234";
    echo json_encode($person);
 ?>
运行结果

(2):使用jsonp的方法:
test01.html代码:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>同源政策测试</title>
</head>
<body>
<input id="btn" type="button" value="读取后台信息"/>
<script type="text/javascript">
    //创建回调函数
    function person(data) {
        console.log(data);
    };
    //添加script标签方法
    function addScript(src){
        var script = document.createElement('script');
        script.setAttribute('type','text/javascript');
        script.src = src;
        document.body.appendChild(script);
    };

    document.querySelector('#btn').addEventListener('click', function(){
        //调用服务器数据
        addScript("http://test02.com/test02.php?callback=person")
      //?号后面就是要搜索的内容,callback="你自定义的回调函数名",将这个请求发送给服务器,服务器会返回这个回调函数方法,将json数据作为参数传给这个方法完成回调,
    });
</script>
</body>
</html>

test02.php代码:

<?php 
    $person = "你的用户名是:xiaoming"." "."你的密码是:abcd1234";
    echo $_GET['callback']."(".json_encode($person).")";
 ?> 
运行结果

本文版权归本人和饥人谷所有,转载请注明来源。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容