跨域的几种解决方法

浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授权情况下,不能读写对方的资源。为了实现跨域获取数据有一下几种方法

1.JSONP

利用script标签可以引入其他域下的js特性,可实现跨域访问接口,需要后端的支持;实现跨域的整个过程:
1.定义数据处理函数_fun
2.创建script标签,src的地址执行后端接口,最后加个参数callback=_fun
3.服务端在收到请求后,解析参数,计算返还数据,输出 fun(data) 字符串。
4.fun(data)会放到script标签做为js执行。此时会调用fun函数,将data做为
前端JS

    $('.change').addEventListener('click',function() {
        var script = document.createElement('script')
        script.src = 'http://localhost:8080/getNews?callback=showNews'
      //创建script标签,把callback=showNews作为参数加进去
        document.head.appendChild(script)
        document.head.removeChild(script)
    })
   //后端收到请求处理后返回showNews(data)
    function showNews(news) {
        var html = ''
        for (var i = 0; i < news.length; i++) {
            html +='<li>' + news[i] + '</li>'
        }
        console.log(html)
        $('.news').innerHTML = html
    }
 function $(id) {
    return document.querySelector(id)
}

服务端要做个判断

var cb = req.query.callback;
    if (cb) {
        res.send(cb + '('+ JSON.stringify(data) +')')
    }else {
        res.send(data)
    }

2.CORS方法

CORS 全称是跨域资源共享(Cross-Origin Resource Sharing),发出XHLHttpRequest请求,实现AJAX跨域使用。实现方式:
当使用XHLHttpRequest发送请求时,该请求不符合同源策略,这是浏览器会给该请求添加一个请求头:Origin,后台进行处理,确定接收请求会在结果中加一个响应头:Access-Control-Allow-Origin; 浏览器判断该相应头中是否包含 Origin 的值,如果有浏览器会处理响应,就可以拿到响应数据,如果不包含Origin的值,就无法拿到数据。cors的表象和同源的ajax请求没啥区别,代码一样。
当前JS代码和ajax一样

var xhr = new XMLHttpRequest()
    xhr.onreadystate = function() {
        if (state === 4) {
            if (status === 200 || status === 304) {
                appendChildHtml(JSON.parse(xhr.responsetext))
            }
        }
        xhr.open('get','http://other.com/getNews',true)
        xhr.send()
    }

    function appendChildHtml(news) {
    }

其他域处理数据

router.get('/getNews',function(req,res){
    var news = []
    var data = []
    for (var i = 0; i < 3; i++) {
        var index = parseInt(Math.random()*news.length)
        data.push(news[index])
        news.splice(index,1)
    }
    res.header("Access-Control-Allow-Origin","http://example.com")
     //允许指定域访问
    res.header("Access-Control-Allow-Origin","*")
     //允许任意域访问
    res.send(data)
})

具体可参考
<a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS#Preflighted_requests">HTTP访问控制(CORS)</a>

3.降域

操作iframe之类的访问其他域,可以用降域方法
一下a.html和b.html都降域处理后可以互相访问了
a.html

<div>
  <div class="main">
    <input type="text" placeholder="http://b.jrg.com:8080/a.html">
  </div>
  <iframe src="http://b.jrg.com:8080/b.html" frameborder="0" ></iframe>
</div>
<script>
//URL: http://a.jrg.com:8080/a.html
//xxx
document.domain = "jrg.com"   //降域处理

b.html

<div>
<input id="input" type="text"  placeholder="http://b.jrg.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
//xxx
document.domain = 'jrg.com';  //降域处理

4.postMessage

window.postMessage() 方法可以安全地实现跨源通信。window.postMessage() 方法被调用时,会向目标窗口发送信息,要接收其他窗口发来的消息时,要为message添加监听事件。
下面a.html和b.html可以互相访问
a.html

<div class="ct">
    <h1>使用postMessage实现跨域</h1>
    <div class="main">
        <input type="text" placeholder="http://a.jrg.com:8080/a.html">
    </div>
    <iframe src="http://localhost:8080/b.html" frameborder="0" ></iframe>
</div>
<script>
//URL: http://a.jrg.com:8080/a.html
$('.main input').addEventListener('input', function(){
    console.log(this.value);
    window.frames[0].postMessage(this.value,'*');
})
window.addEventListener('message',function(e) {
        $('.main input').value = e.data
    console.log(e.data);
});
function $(id){
    return document.querySelector(id);
}

b.html

<input id="input" type="text"  placeholder="http://b.jrg.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
 
$('#input').addEventListener('input', function(){
    window.parent.postMessage(this.value, '*');
})
window.addEventListener('message',function(e) {
        $('#input').value = e.data
    console.log(e.data);
});
function $(id){
    return document.querySelector(id);
}   
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 什么是同源策略? 同源策略是指,浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授...
    upup_dayday阅读 271评论 0 0
  • 什么是跨域 浏览器出于安全方面的考虑,只允许客户端与本域(同协议、同域名、同端口,三者缺一不可)下的接口交互。不同...
    七里之境阅读 1,385评论 0 0
  • 什么是同源策略 同源政策(same-origin policy)是指同域名(或ip),同端口,同协议视为同一个域,...
    小囧兔阅读 562评论 0 1
  • 远程工作的好处 可以让员工自主选择适合自己的工作环境 可以使员工省下在路上的时间 可以让员工灵活支配时间,把工作融...
    ba帝儿阅读 634评论 0 0
  • 周问渔阅读 222评论 0 0