You don't know cross-origin

cross-origin

Why

爲何會存在跨域問題
  • 同源策略

因爲出於安全考慮,瀏覽器規定JavaScript不能操做其餘域下的頁面DOM,不能接受其餘域下的xhr請求(不僅是js,引用非同域下的字體文件,還有canvas引用非同域下的圖片,也被同源策略所約束)
只要協議、域名、端口有一者不一樣,就被視爲非同域。css

How

如何解決

要解決跨域問題,就要繞過瀏覽器對js的限制,另闢蹊徑html

  1. JSONP

這是最簡單,也是最流行的跨域解決方案,它利用script標籤不受同源策略的影響,解決跨域,須要後臺配合,返回特殊格式的數據前端

前端git

<script>
    function JSONP(link) {
        let script=document.createElement("script");
        script.src=link;
        document.body.appendChild(script);
    }

    function getUser(data) {
        console.log(data);// todo
    }
    const API_URL_USER='http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=getUser'; // 這裏以愛奇藝的接口爲例(來源網絡,侵刪)
    JSONP(API_URL_USER);
</script>

後端github

// Express(Nodejs)
// mock data
const USERS=[
    {name:"Tom",age:23},
    {name:"Jack",age:23}
];

app.get("/user",function (req,res) {
    let cbName=req.query["callback"];
    // 這裏作一個容錯處理
    res.send(`
        try{
            ${cbName}(${JSON.stringify(USRES)});
        }catch(ex) {
            console.error("The data is invalid");
        }
    `);
});
  1. CORS (cross-origin resource sharing)

跨域資源共享,是W3C的一個標準,它容許瀏覽器發送跨域服務器的請求,CORS須要瀏覽器和服務器同時支持json

後端canvas

簡單請求和非簡單請求詳情,請閱讀阮一峯老師的博文,這裏再也不敖述segmentfault

app.use(function (req,res,next){
    res.header('Access-Control-Allow-Origin', 'http://localhost:6666'); // 容許跨域的白名單,通常不建議使用 * 號
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); // 容許請求的方法,非簡單請求,會進行預檢
    res.header('Access-Control-Allow-Headers', 'Content-Type'); // 容許請求攜帶的頭信息,非簡單請求,會進行預檢
    res.header('Access-Control-Allow-Credentials','true'); // 容許發送cookie,這裏前端xhr也須要一塊兒配置 `xhr.withCredentials=true`
    next();
});
  1. 代理

只要是在與你同域下的服務器,新建一個代理(服務端不存在同源策略),將你的跨域請求所有代理轉發後端

後端api

const proxy=require("http-proxy-middleware"); // 這裏使用這個中間件完成代理
app.use('/api', proxy("http://b.com")); // http://a.com/api -> http://b.com/api
  1. window.name+iframe

MDN裏解釋道它是獲取/設置窗口的名稱,由於的它在不一樣頁面甚至域名加載後值都不會改變,該屬性也被用於做爲 JSONP 的一個更安全的備選來提供跨域通訊(cross-domain messaging)

前端

<!--http://a.com/page1.html-->
<script>
    function request(url,callback) {
        let iframe=document.createElement("iframe");
        let isFirst=true;
        iframe.style.display="none";
        iframe.addEventListener("load",function () {
            if (isFirst) { 
                isFirst=false; // 防止iframe循環加載
                iframe.src="http://a.com/page2.html";
                callback && callback(iframe.contentWindow.name);
                iframe.remove();               
            }
        });
        iframe.src=url;
    }

    requeset("http://b.com/user",function (data) {
        console.log(data); // todo
    });
</script>

後端

// Express(Nodejs)
// mock data
const USERS=[
    {name:"Tom",age:23},
    {name:"Jack",age:23}
];

app.get("/user",function (req,res) {
    res.send(`
        <script>
            ;window.name=${JSON.stringify(USERS)};
        </script>
    `);
});
  1. document.domian

這個使用狀況有限,例如
http://a.c.com
http://b.c.com
主域相同時,分別設置他們頁面的document.domain="c.com";

  1. locaction.hash+iframe

嵌套兩層iframe,達到第一層與第三層同域,就能夠互相通訊了

<!--http://a.com/page1.html-->
<script>
    let iframe=document.createElement("iframe");
    iframe.style.display="none";
    iframe.src="http://b.com/user.html";

    window.addEventListener("hashchange",function () {
        console.log(location.hash.slice(1)); // todo
    });
</script>
<!--http://b.com/user.html-->
<script>
    let iframe=document.createElement("iframe");
    iframe.style.display="none";

    function getUserData() {
        fetch("http://b.com/user")
            .then(res=>{
                let data=res.json();
                iframe.src=`http://a.com/page2.html#${data}`;
            });
    }

    getUserData();

    window.addEventListener("hashchange",function () {
        getUserData();
    });
</script>
<script>
    top.location.hash=window.location.hash;
</script>
  1. 圖片ping

這個只能發出去請求,沒法獲取到服務器的響應,經常用於網站流量統計

let img=new Image();
img.addEventListener("load",function () {
    console.log("Send success"); // todo
});
img.src="http://site.c.com/a.gif?count=666";
  1. postMessage+iframe
<!-- http://a.com -->
<button id="sendBtn">從B接口獲取用戶數據</button>
<iframe src="http://b.com" id="ifr"></iframe>
<script>
window.addEventListener("message",function({detail,origin}){
    if (origin==="http://b.com") { // 最好判斷下消息來源
        if (detail.type==="set-user") {
            console.log(detail.data); // todo
        }
    }
});

sendBtn.addEventListener("click",function () {
    ifr.contentWindow.postMessage({
        type:"get-user",
    },"http://b.com");
});
</script>
<!-- http://b.com -->
<script>
window.addEventListener("messagae",function({detail,origin}){
    if (origin==="http://a.com") { // 最好判斷下消息來源
        if (detail.type==="get-user") {
            fetch("http://b.com/user")
            .then(res=>{
                top.contentWindow.postMessage({
                    type:"set-user",
                    data:res.json(), // 假設接口返回的是json格式的數據
                },"http://a.com");
            })
        }
    }
});


</script>
  1. postMessage+form+iframe

這個須要後臺配合返回特殊格式的數據,TL,DR 能夠看這個demo

  1. WebSocket

WebSocket是一種通訊協議,該協議不實行同源政策,
注意須要瀏覽器和服務器都支持的狀況下

<script src="//cdn.bootcss.com/socket.io/1.7.2/socket.io.min.js"></script>
 <script>
    var io = io.connect('http://b.com');
    io.on('data', function (data) {
        console.log(data); // 接受來自服務器的消息
    });
</script>

後端

// Nodejs
const server = require('http').createServer();
const io = require('socket.io')(server);

io.on('connection', function (client) {
    client.emit('data', 'This message from "http://b.com"');
});

Summary

  • 目前我的在工做中遇到的解決方法就是這些,固然還有許多其餘的方法,你看,其實跨域並不難吧 ^_^
  • js經過xhr發的跨域請求,雖然得不到響應,可是能夠發送出去,其實若是是單向通訊的話,也能夠,好比文章閱讀統計,網站流量統計

Reference

跨域資源共享 CORS 詳解---阮一峯
不要再問我跨域的問題了
FatDong1/cross-domain

相關文章
相關標籤/搜索