1. 程式人生 > 程式設計 >js前端解決跨域的八種實現方案

js前端解決跨域的八種實現方案

由於同源策略的限制,滿足同源的指令碼才可以獲取資源。雖然這樣有助於保障網路安全,但另一方面也限制了資源的使用。
那麼如何實現跨域呢,以下是實現跨域的一些方法。

一、jsonp跨域

原理:script標籤引入js檔案不受跨域影響。不僅如此,帶src屬性的標籤都不受同源策略的影響。

正是基於這個特性,我們通過script標籤的src屬性載入資源,資料放在src屬性指向的伺服器上,使用json格式。

由於我們無法判斷script的src的載入狀態,並不知道資料有沒有獲取完成,所以事先會定義好處理函式。服務端會在資料開頭加上這個函式名,等全部載入完畢,便會呼叫我們事先定義好的函式,這時函式的實參傳入的就是後端返回的資料了。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    function callback(data) {
      alert(data.test);
    }
  </script>
  <script src="./jsonp.js"></script>
</body>
</html>

jsonp.js

callback({"test": 0});

訪問index.html彈窗便會顯示0
該方案的缺點是:只能實現get一種請求。

二、document.domain + iframe跨域

此方案僅限主域相同,子域不同的應用場景。

比如百度的主網頁是www.baidu.com,zhidao.baidu.com、news.baidu.com等網站是www.baidu.com這個主域下的子域。

實現原理:兩個頁面都通過js設定document.domain為基礎主域,就實現了同域,就可以互相操作資源了。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <iframe src="https://mfaying.
github
.io/lesson/cross-origin/document-domain/child.html"></iframe> <script> document.domain = 'mfaying.github.io'; var t = '0'; </script> </body> </html>

child.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    document.domain = 'mfaying.github.io';
    alert(window.parent.t);
  </script>
</body>
</html>

三、location.hash + iframe跨域

父頁面改變iframe的src屬性,location.hash的值改變,不會重新整理頁面(還是同一個頁面),在子頁面可以通過window.localtion.hash獲取值。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <iframe src="child.html#" style="display: none;"></iframe>
  <script>
    var oIf = document.getElementsByTagName('iframe')[0];
    document.addEventListener('click',function () {
      oIf.src += '0';
    },false);
  </script>
</body>
</html>

child.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    window.onhashchange = function() {
      alert(window.location.hash.slice(1));
    }
  </script>
</body>
</html>

點選index.html頁面彈窗便會顯示0

四、window.name + iframe跨域

原理:window.name屬性在不同的頁面(甚至不同域名)載入後依舊存在,name可賦較長的值(2MB)。
在iframe非同源的頁面下設定了window的name屬性,再將iframe指向同源的頁面,此時window的name屬性值不變,從而實現了跨域獲取資料。

./parent/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    var oIf = document.createElement('iframe');
    oIf.src = 'https://mfaying.github.io/lesson/cross-origin/window-name/child.html';
    var state = 0;
    oIf.onload = function () {
      if (state === 0) {
        state = 1;
        oIf.src = 'https://mfaying.github.io/lesson/cross-origin/window-name/parent/proxy.html';
      } else {
        alert(JSON.parse(oIf.contentWindow.name).test);
      }
    }
    document.body.appendChild(oIf);
  </script>
</body>
</html>

./parent/proxy.html

空檔案,僅做代理頁面

./child.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    window.name = '{"test": 0}'
  </script>
</body>
</html>

五、postMessage跨域

postMessage是HTML5提出的,可以實現跨文件訊息傳輸。
用法
getMessageHTML.postMessage(data,origin);
data: html5規範支援的任意基本型別或可複製的物件,但部分瀏覽器只支援字串,所以傳參時最好用JSON.stringify()序列化。

origin: 協議+主機+埠號,也可以設定為程式設計客棧"*",表示可以傳遞給任意視窗,如果要指定和當前視窗同源的話設定為"/"。
getMessageHTML是我們對於要接受資訊頁面的引用,可以是iframe的cont程式設計客棧entWindow屬性、window.open的返回值、通過name或下標從window.frames取到的值。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
    <iframe id='ifr' src='./child.html' style="display: none;"></iframe>
    <button id='btn'>click</button>
    <script>
      var btn = document.getElementById('btn');
      btn.addEventListener('click',function () {
        varwww.cppcns.com ifr = document.getElementById('ifr');
        ifr.contentWindow.postMessage(0,'*');
      },false);
    </schttp://www.cppcns.comript>
</body>
</html>

child.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
    <script>
      window.addEventListener('message',function(event){
        alert(event.data);
      },false);
    </script>
</body>
</html>

點選index.html頁面上的按鈕,彈窗便會顯示0。

六、跨域資源共享(CORS)

只要在服務端設定Access-Control-Allow-Origin就可以實現跨域請求,若是cookie請求,前後端都需要設定。
由於同源策略的限制,所讀取的cookie為跨域請求介面所在域的cookie,並非當前頁的cookie。
CORS是目前主流的跨域解決方案。

原生node.js實現

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script
    src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
    crossorigin="anonymous"></script>
</head>
<body>
  <script>
    $.get('http://localhost:8080',function (data) {
      alert(data);
    });
  </script>
</body>
</html>

server.js

var http = require('http');
var server = http.createServer();

server.on('request',function(req,res) {
  res.writeHead(200,{
    'Access-Control-Allow-Credentials': 'true',// 後端允許傳送Cookie
    'Access-Control-Allow-Origin': 'https://mfaying.github.io',// 允許訪問的域(協議+域名+埠)
    'Set-Cookie': 'key=1;Path=/;Domain=mfaying.github.io;HttpOnly'   // HttpOnly:指令碼無法讀取cookie
  });

  res.write(JSON.stringify(req.method));
  res.end();
});

server.listen('8080');
console.log('Server is running at port 8080...');

koa結合koa2-cors中介軟體實現

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script
    src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
    crossorigin="anonymous"></script>
</head>
<body>
  <script>
    $.get('http://localhost:8080',function (data) {
      alert(data);
    });
  </script>
</body>
</html>

server.js

var koa = require('koa');
var router = require('koa-router')();
const cors = require('koa2-cors');

var app = new koa();

app.use(cors({
  origin: function (ctx) {
    if (ctx.url === '/test') {
      return false;
    }
    return '*';
  },exposeHeaders: ['WWW-Authenticate','Server-Authorization'],maxAge: 5,credentials: true,allowMethods: ['GET','POST','DELETE'],allowHeaders: ['Content-Type','Authorization','Accept'],}))

router.get('/',async function (ctx) {
  ctx.body = "0";
});

app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen(3000);
console.log('server is listening in port 3000');

七、WebSocket協議跨域

WebSocket協議是HTML5的新協議。能夠實現瀏覽器與伺服器全雙工通訊,同時允許跨域,是服務端推送技術的一種很好的實現。

前端程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    var ws = new WebSocket('ws://localhost:8080/','echo-protocol');
    // 建立連線觸發的事件
    ws.onopen = function () {
      var data = { "test": 1 };
      ws.send(JSON.stringify(data));// 可以給後臺傳送資料
    };
 
    // 接收到訊息的回撥方法
    ws.onmessage = function (event) {
      alert(JSON.parse(event.data).test);
    }
 
    // 斷開連線觸發的事件
    ws.onclose = function () {
      conosle.log('close');
    };
  </script>
</body>
</html>

server.js

var WebSocketServer = require('websocket').server;
var http = require('http');
 
var server = http.createServer(function(request,response) {
  response.writeHead(404);
  response.end();
});
server.listen(8080,function() {
  console.log('Server is listening on port 8080');
});
 
wsServer = new WebSocketServer({
    httpServer: server,autoAcceptConnections: false
});
 
function originIsAllowed(origin) {
  return true;
}
 
wsServer.on('request',function(request) {
    if (!originIsAllowed(request.origin)) {
      request.reject();
      console.log('Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept('echo-protocol',request.origin);
    console.log('Connection accepted.');
    connection.on('message',function(message) {
      if (message.type === 'utf8') {
        const reqData = JSON.parse(message.utf8Data);
        reqData.test -= 1;
        connection.sendUTF(JSON.stringify(reqData));
      }
    });
    connection.on('close',function() {
      console.log('close');
    });
});

八、nginx代理跨域

原理:同源策略是瀏覽器的安全策略,不是HTTP協議的一部分。伺服器端呼叫HTTP介面只是使用HTTP協議,不存在跨越問題。

實現:通過nginx配置代理伺服器(域名與test1相同,埠不同)做跳板機,反向代理訪問test程式設計客棧2介面,且可以修改cookie中test資訊,方便當前域cookie寫入,實現跨域登入。
nginx具體配置:

#proxy伺服器
server {
    listen       81;
    server_name  www.test1.com;

    location / {
        proxy_pass   http://www.test2.com:8080;  #反向代理
        proxy_cookie_test www.test2.com www.test1.com; #修改cookie裡域名
        index  index.html index.htm;

        add_header Access-Control-Allow-Origin http://www.test1.com;  #當前端只跨域不帶cookie時,可為*
        add_header Access-Control-Allow-Credentials true;
    }
}

到此這篇關於js前端解決跨域的八種實現方案的文章就介紹到這了,更多相關js 跨域內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!