跨域

作者: 普莱那 | 来源:发表于2017-03-12 00:12 被阅读14次

题目1: 什么是同源策略

浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授权的情况下,不能读写对方的资源。

本域指的是?

同协议:如都是http,https,file,ssh,mailto,tel
同域名(在//后到第一个/之间):
如都是http://jirengu.com/ahttp://jirengu.com/b
同端口:如都是80端口
如:http://jirengu.com/a/b.jshttp://jirengu.com/index.php (同源)

不同源的例子:
http://jirengu.com/main.jshttps://jirengu.com/a.php (协议不同)
http://jirengu.com/main.jshttp://bbs.jirengu.com/a.php (域名不同,域名必须完全相同才可以)
http://jiengu.com/main.jshttp://jirengu.com:8080/a.php (端口不同,第一个是80)

需要注意的是: 对于当前页面来说页面存放的 JS 文件的域不重要,重要的是加载该 JS 页面所在什么域

题目2: 什么是跨域?跨域有几种实现形式

  • 什么是跨域?
    允许不同域的接口进行交互

  • 跨域有几种实现形式

  1. JSONP
  2. CORS
  3. 降域
  4. postMessage

题目3: JSONP 的原理是什么

web页面中,通过script标签获取js代码可以跨域进行,我们可以动态的创建script标签,设置src属性指向我们请求资源的url地址,然后放到head标签中。这样就可以把不同域的数据加载到本域名下,不过需要后端支持jsonp,也就是通过前端的url中的callback参数动态的生成回调函数名,通过传参的形式执行获取到的数据,这样的话,前端预定义好的函数就可以让传来的数据自动运行。

题目4: CORS是什么

CORS(Cross Origin Resoure Sharing)跨域资源共享。由于浏览器的同源策略,当前端用 XMLHttpRequest 跨域访问时,浏览器会在请求头中添加:origin
后端会添加一个响应头:Access-Control-Allow-Origin
浏览器判断该相应头中Access-Control-Allow-Origin的值是否包含 Origin 的值,如果有则浏览器会处理响应,我们就可以拿到响应数据,如果不包含浏览器直接驳回,这时我们无法拿到相应数据。

题目5: 根据视频里的讲解演示三种以上跨域的解决方式

JSONP
前端代码
var script = document.createElement('script');
script.src = 'http://example.com/getnews?callback=dosth';
document.head.appendChild(script);
后端代码:
app.get('/getnews',function(req,res){
    var cb = req.query.callback;
    var ret = cb + "(" + JSON.stringify(dataToBeTransfered) + ")";
    res.send(ret);
});
JSONP
CORS
前端代码
var xhr = new XMLHttpRequest()
xhr.open('GET','http://example.com/cors?para=para1&para=para2');
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
        if(xhr.status === 200 || xhr.status === 304){
            var ret = xhr.responseText;
            doSthWith(ret);
        }
    }
}
xhr.send();
后端代码 
app.get('/cors',function(req,res){

    var ret = JSON.stringify(dataToBeTransfered);
    res.header('access-control-allow-origin','http://example.com');
    res.send(ret);
});
CORS
降域
a.peng.com域名下的a.html代码:
<body>
<h1>使用降域名实现跨域</h1>
<div class="main">
  <input type='text' placeholder='http:a.peng.com:8080/a.html'>
  
</div>
<iframe src="http://b.peng.com:8080/b.html" frameborder='0'></iframe>
<script type="text/javascript">
  document.querySelector('.main input').addEventListener('input',function(){
    console.log(this.value);
    window.frames[0].document.querySelector('input').value=this.value;
  });
  document.domain = 'peng.com';
</script>
</body>

b.peng.com域名下的b.html代码:
<body>
<div class="main">
  <input type='text' placeholder='http:b.peng.com:8080/a.html'>
  
</div>

<script type="text/javascript">

  document.domain = 'peng.com';
</script>
降域
  1. postMessage

相关文章

网友评论

      本文标题:跨域

      本文链接:https://www.haomeiwen.com/subject/ftpzgttx.html