跨域

2017-04-23  本文已影响0人  LINPENGISTHEONE

1: 什么是同源策略

http://www.jirengu.com/dir2/other.html:同源
http://jirengu.com/dir/other.html:不同源(域名不同)
http://v2.www.jirengu.com/dir/other.html:不同源(域名不同)
http://www.jirengu.com:81/dir/other.html:不同源(端口不同)

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

3: JSONP 的原理是什么

4: CORS是什么

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

//浏览器端
var jsonp = document.createElement("script");    //创建一个script标签
jsonp.src = "http://www.test.com:8080/getdata?callbackName=callback"; //设置src地址
document.getElementsByTagName("head")[0].appendChild(jsonp); //将script放在head里面

//定义callback函数
function callback(args){
    console.log(args);
    console.log("JSONP跨域成功")
}

//服务器端
app.get('/getdata', function(req, res){
    var data = {a: 1,};
    res.send(req.query.callbackName + '(' + JSON.stringify(data) + ')');
})
//浏览器端
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
        if(xhr.status === 200 || xhr.status === 304){
            var result = JSON.parse(xhr.responseText);
            console.log(result);
            console.log("CORS跨域成功");
        }
    }
}
xhr.open("GET", "http://b.test.com:8080/getdata/"); //从http://b.test.com:8080/getdata/获取数据
xhr.send();

//服务端
app.get('/getdata', function(req, res){
  var data = {a: 1,};
  res.header("Access-Control-Allow-Origin", "http://a.test.com:8080"); //后台允许http://a.test.com:8080请求数据
  res.send(data);
})
//在主页面http://a.test.com/a.html 中设置document.domain
    document.domain = 'test.com';
    var iframeWindow = document.getElementById('iframe').contentWindow
//在被Iframe引入的页面 http://b.test.com/b.html 中也设置document.domain
    document.domain = 'test.com'
//主页面http://a.test.com/a.html
    var iframeWindow =document.getElementById('iframe').contentWindow;
    iframeWindow.postMessage("some Messages", "*");
//在被Iframe引入的页面 http://b.test.com/b.html 
    window.onmessage = function(e) {
        e = e || event;
        console.log(e.data);
    }
上一篇 下一篇

猜你喜欢

热点阅读