三種以上跨域的解決方式

第一種JSONP

在html下引入外界地址的script標(biāo)簽是可行的,可以引入jquer庫等,那說明說同源策略并沒有對script的src進行監(jiān)測,所以可以通過script的src引入外界的地址,通過script 去后臺訪問數(shù)據(jù),將訪問的數(shù)據(jù),通過后臺的配合,將后臺返回的數(shù)據(jù)當(dāng)做js去運行。

代碼例子:

 <!DOCTYPE html>
<html>
  <head>
       <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
      <title>news</title>
<style>
    .container{
        width: 900px;
        margin: 0 auto;
    }
</style>
</head>
<body>
<div class="container">
<ul class="news">
    <li>第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)</li>
    <li>男雙力爭會師決賽 </li>
    <li>女排將死磕巴西!</li>
</ul>
<button class="change">換一組</button>
</div>

<script>

$('.change').addEventListener('click', function(){
    var script = document.createElement('script');
    script.src = 'http://127.0.0.1:8080/getNews?callback=appendHtml';
    document.head.appendChild(script);
    document.head.removeChild(script);
})
function appendHtml(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);
}
</script>

后臺代碼

  將后臺返回的數(shù)據(jù),作為參數(shù)傳給函數(shù)appendHtml,然后調(diào)用函數(shù)appendHtml執(zhí)行。從而獲得了后臺返回的數(shù)據(jù),實現(xiàn)了跨域。

app.get('/getNews', function(req, res){

var news = [
    "第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)200米羽球",
    "正直播柴飚/洪煒出戰(zhàn) 男雙力爭會師決賽",
    "女排將死磕巴西!郎平安排男陪練模仿對方核心",
    "沒有中國選手和巨星的110米欄 我們還看嗎?",
    "中英上演奧運金牌大戰(zhàn)",
    "博彩賠率挺中國奪回第二紐約時報:中國因?qū)κ址幎鴣G失的獎牌最多",
    "最“出柜”奧運?同性之愛閃耀里約",
    "下跪拜謝與洪荒之力一樣 都是真情流露"
]
var data = [];
for(var i=0; i<3; i++){
    var index = parseInt(Math.random()*news.length);
    data.push(news[index]);
    news.splice(index, 1);
}
var cb = req.query.callback;
//判斷是否有callback如果有,返回appendHtml(JSON.stringify(data))這樣html就能以執(zhí)行js方式調(diào)用函數(shù) appendHtml
if(cb){
    res.send(cb + '('+ JSON.stringify(data) + ')');
}else{
    res.send(data);
}
})

第二種CORS

CORS全稱Cross-Origin Resource Sharing,定義了在必須訪問跨域資源時,瀏覽器與服務(wù)器要如何溝通。原理是使用自定義的的HTTP頭部讓瀏覽器與服務(wù)器溝通,從而決定請求或相應(yīng)是否成功。比如在發(fā)送一個簡單的get請求時,需要給它附加一個額外的origin頭部,其中包含請求頁面的源信息,以便讓服務(wù)器根據(jù)這個頭部信息決定是否給予響應(yīng)。

    只需要后臺做配置,設(shè)置可以允許的 origin

// res.header("Access-Control-Allow-Origin", "http://a.jrg.com:8080");
這樣a.jrg.com:8080的網(wǎng)站前來訪問就可以接受,并給返回數(shù)據(jù)。
允許網(wǎng)頁地址是http://a.jrg.com:8080來訪問接口要數(shù)據(jù)
res.header("Access-Control-Allow-Origin", "*");
// 允許任何網(wǎng)站前來要數(shù)據(jù)。
代碼例子 :

      <!DOCTYPE html>
     <html>
      <head>
          <meta charset="utf-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
          <title>news</title>
          <style>
                .container{
                width: 900px;
              margin: 0 auto;
         }
      </style>
</head>
<body>
      <div class="container">
        <ul class="news">
        <li>第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)</li>
        <li>男雙力爭會師決賽 </li>
        <li>女排將死磕巴西!</li>
  </ul>
<button class="change">換一組</button>
 </div>
  <script>

$('.change').addEventListener('click', function(){
    var xhr = new XMLHttpRequest();
    xhr.open('get', 'http://b.jrg.com:8080/getNews', true);
    xhr.send();
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200 ||xhr.status ===304){
            appendHtml( JSON.parse(xhr.responseText) )
        }
    }
    window.xhr = xhr
})
function appendHtml(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);
}
</script>
</html>


  app.get('/getNews', function(req, res){
var news = [
    "第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)200米羽球",
    "正直播柴飚/洪煒出戰(zhàn) 男雙力爭會師決賽",
    "女排將死磕巴西!郎平安排男陪練模仿對方核心",
    "沒有中國選手和巨星的110米欄 我們還看嗎?",
    "中英上演奧運金牌大戰(zhàn)",
    "博彩賠率挺中國奪回第二紐約時報:中國因?qū)κ址幎鴣G失的獎牌最多",
    "最“出柜”奧運?同性之愛閃耀里約",
    "下跪拜謝與洪荒之力一樣 都是真情流露"
]
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://a.jrg.com:8080");
 res.header("Access-Control-Allow-Origin", "*");
 console.log("111111");
 res.send(data);
})

第三種降域

 a.html
              <!doctype html>
                         <html lang="en">
            <head>
                     <meta charset="UTF-8">
                    <title>Document</title>
    <style>
        .ct{
            width: 910px;
            margin: auto;
        }
        .main{
            float: left;
            width: 450px;
            height: 300px;
            border: 1px solid #ccc;
        }
        .main input{
            margin: 20px;
            width: 200px;
        }
        .iframe{
            float: right;
        }
        iframe{
            width: 450px;
            height: 300px;
            border: 1px dashed #ccc;
        }
       </style>
    </head>
    <body>

    <div class="ct">
        <h1>使用降域?qū)崿F(xiàn)跨域</h1>
        <div class="main">
            <input type="text" placeholder="http://a.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
        document.querySelector('.main input').addEventListener('input', function(){
            console.log(this.value);
            window.frames[0].document.querySelector('input').value = this.value;
        })
        document.domain = "jrg.com"
    </script>
     </body>
    </html>


  b.html

    <!doctype html>
     <html lang="en">
      <head>
       <meta charset="UTF-8">
       <title>Document</title>
     <style>
        html,body{
            margin: 0;
        }
        input{
            margin: 20px;
            width: 200px;
        }
    </style>
    </head>
     <body>
         <input id="input" type="text"  placeholder="http://b.jrg.com:8080/b.html">
     <script>
      // URL: http://b.jrg.com:8080/b.html

    document.querySelector('#input').addEventListener('input', function(){
        window.parent.document.querySelector('input').value = this.value;
    })
     document.domain = 'jrg.com';
     </script>
     </body>
     </html>

document.domain = "jrg.com" 通過這行代碼,將兩個網(wǎng)站的都降級為jrg.com 所以屬于同源了,可以相互訪問數(shù)據(jù)。

第四種postMessage() 是用主動發(fā)送 和主動接收的方式


  <html>
<style>
    .ct{
        width: 910px;
        margin: auto;
    }
    .main{
        float: left;
        width: 450px;
        height: 300px;
        border: 1px solid #ccc;
    }
    .main input{
        margin: 20px;
        width: 200px;
    }
    .iframe{
        float: right;
    }
    iframe{
        width: 450px;
        height: 300px;
        border: 1px dashed #ccc;
    }
</style>

<div class="ct">
    <h1>使用postMessage實現(xiàn)跨域</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
// 給其他網(wǎng)站主動發(fā)送數(shù)據(jù)。有監(jiān)聽的網(wǎng)站,可以接受到數(shù)據(jù)。
$('.main input').addEventListener('input', function(){
    console.log(this.value);
    window.frames[0].postMessage(this.value,'*');
})

//監(jiān)聽 并接受返回的數(shù)據(jù)??梢杂胑.data接收。
window.addEventListener('message',function(e) {
        $('.main input').value = e.data
    console.log(e.data);
});
function $(id){
    return document.querySelector(id);
}
</script>
</html>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容