Four kinds of commonly used

  1. Cross-domain Resource Sharing (CORS)
  2. Nginx agents cross domains
  3. Nodejs middleware proxies cross domains
  4. The browser blocks security verification

6 are not commonly used

  1. Cross domains via JSONP
  2. PostMessage cross-domain
  3. The WebSocket protocol is cross-domain
  4. Document.domain + iframe cross domain
  5. location.hash + iframe
  6. Window. name + iframe cross domain

1. Cross-domain Resource Sharing (CORS)

  • The server must set access-Control-allow-origin to *
  • If the client need to use cookies, you will need to set axios. Defaults. The withCredentials = true

2. Nginx proxy is cross-domain

Access under the same domain name and port through the nginx proxy.

server {
   listen       80;
   # server_name  www.josephxia.com;
   location / {
       root   /var/www/html;
       index  index.html index.htm;
       try_files $uri $uri/ /index.html;
   }

   location /api {
           proxy_pass  http:/ / 127.0.0.1:3000;proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}Copy the code

3. Nodejs middleware proxy is cross-domain

Start service A locally, forward the content to request B to service A locally, and perform all subsequent processing on service A. The principle is similar to nginx direction proxy.

  / / webpack configuration
  devServer: {proxy: {"/api/": {target:"http://localhost:7001".secure:false.pathRewrite: {'^/api':""}}}}Copy the code

4. The browser blocks security verification

  1. Google Chrome blocks cross domains directly

open -n /Applications/Google\ Chrome.app/ –args –disable-web-security –user-data-dir=/Users/jason_pro/Documents/ChormConfig

  1. Google Chrome Windows blocks cross domain

Google -> Properties -> Target -> C:\Users\ XXXXXX \AppData\Local\Google\Chrome\Application\ Chrome –user-data-dir=d:\MyChromeDevUserData

5. Cross domains through JSONP

By dynamically creating a script, and then request a reference url to achieve cross-domain communication. The corresponding JS code needs to be generated by the server. Client pass

 var script = document.createElement('script');
script.type = 'text/javascript'; 
script.src = ' '// The server returns js
Copy the code

6. PostMessage across domains

PostMessage is an API in HTML5 that supports popup, multi-window, multi-iframe data interaction

  • The postMessage(data, Origin) method takes two arguments
  • Data: Can be an object or a string. Some browsers only support strings
  • Origin: protocol + host + port number. The value can also be set to “*”, which indicates that the origin file can be sent to any window. If the origin file is set to “/”, the origin file can be sent to any window.
/ / a.html:http://www.demo1.com/a.html
<iframe id="iframe" src="http://www.demo2.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
        var data = {
            name: 'xxx'
        };
        // Send cross-domain data to domain2
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.demo2.com');
    }; 
    // Accept data from domain2
    window.addEventListener('message'.function(e) {
        alert('data from demo2 ---> ' + e.data);
    }, false);
</script> 


// b.html:http://www.demo2.com/b.html
<script>
    // Receive data from domain1
    window.addEventListener('message'.function(e) {
        alert('data from demo1 ---> ' + e.data); 
        var data = JSON.parse(e.data);
        if (data) {
            data.number = 16; 
            // Send it back to domain1
            window.parent.postMessage(JSON.stringify(data), 'http://www.demo1.com'); }},false);
</script> 
Copy the code

7. WebSocket protocol is cross-domain

  • WebSocket Protocol is the new HTML5 protocol. Full duplex communication between browser and server, cross-domain support, you can use the third party library socket.io
  • A. HTML register socket service C, cross – domain B. HTML register socket service C as well
  • The server pushes messages to A and B at the same time to realize cross-domain data transmission, which is similar to the chat room principle
C / / service node. Js http://api.baidu.com:3000
const express = require('express') ()const http = require('http').Server(express)
const socketIO = require("socket.io")(http)// Since the argument can only be HTTP, it needs to be converted to the traditional HTTP library

socketIO.on('connection'.(socket) = > { // Closure processing after each user opens the page connects
    // Socket is the currently open page client
    // Add a listener to the message method
    socket.on("chat message".(msg) = > {
        // Send a broadcast to everyone
        socketIO.emit("chat message",msg);
    })
    socket.on("disconnection".() = > {
        console.log("Link broken")})})// Note that HTTP startup is used because stocketIO is bound to HTTP
http.listen(3000.() = > {
    console.log("Startup 3000 successful")})Copy the code

a.html www.demo1.com/a.html

<! DOCTYPEhtml>
<html>
  <head>
    <title>Socket.IO chat</title> 
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" /><button>Send</button>
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
    <script>
      $(function() {
        var socket = io("api.baidu.com:3000"); 
        $("form").submit(function(e) {
          e.preventDefault(); // Avoid form submission behavior
          socket.emit("chat message", $("#m").val());
          $("#m").val("");
          return false;
        });

        socket.on("chat message".function(msg) {$("#messages").append($("<li>").text(msg));
        });
      });
    </script>
  </body>
</html>
Copy the code

b.html :www.demo2.com/b.html

<! DOCTYPEhtml>
<html>
  <head>
    <title>Socket.IO chat</title> 
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" /><button>Send</button>
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
    <script>
      $(function() {
        var socket = io("api.baidu.com:3000"); 
        $("form").submit(function(e) {
          e.preventDefault(); // Avoid form submission behavior
          socket.emit("chat message", $("#m").val());
          $("#m").val("");
          return false;
        });
        socket.on("chat message".function(msg) {$("#messages").append($("<li>").text(msg));
        });
      });
    </script>
  </body>
</html>
Copy the code

8 Document. domain + iframe cross-domain

It can be applied only in cross-domain scenarios where the primary domain is the same but the subdomains are different. For example :www.baidu.com, api.baidu.com A parent window :www.baidu.com

<iframe id="iframe" src="http://www.baidu.com/b.html"></iframe>
<script>
    document.domain = 'baidu.com';
    var user = 'admin';
</script>
Copy the code

B Sub-window: api.baidu.com

<script> document.domain = 'baidu.com'; Alert ('get js data from parent --> '+ window.parent. User); </script> </script>Copy the code

9. location.hash + iframe

By saying that A and B are cross-domain relations, and A and C are co-domain,

  • User A directly sends the hash to user B using the iframe.
  • B passes information to A through C as an intermediary

  1. Page A is sent to page B using the HASH url, and the common method called by C is preserved
  2. The B page is always listening for hash changes, passing in the embedded C page
  3. Page C keeps listening for hash changes and calls parent. Parent directly to tell page A

The relevant code

1.) A.HTML: www.domain1.com/a.html

<iframe id="iframe" src="http://www.demo2.com/b.html" style="display:none;" ></iframe> <script> var iframe = document.getElementById('iframe'); SetTimeout (function() {iframe.src = iframe.src + '#user=admin'; }, 1000); Function onCallback(res) {alert('data from c.html --> '+ res); } </script>Copy the code

2.) B.HTML: www.demo2.com/b.html

<iframe id="iframe" src="http://www.demo1.com/c.html" style="display:none;" ></iframe> <script> var iframe = document.getElementById('iframe'); Onhashchange = function () {ifame. SRC = ifame. SRC + location.hash; }; </script>Copy the code

3.) C. HTML: www.demo1.com/c.html

<script>
    window.onhashchange = function () {
        window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
    };
</script>
Copy the code

10 Window. name + iframe Cross domain

  • Window. name persists after loading different domain names on different pages. The value is about 2M
  • A.h HTML by iframe to access cross-domain b.h HTML, and visit with the domain of proxy. HTML, then you can pass the iframe. ContentWindow. Name.

steps

  1. B.html set window.name = ‘XXXXX’ to record what to pass to A.html
  2. Create IFRME access to cross-domain B.HTML,
  3. After loading b.HTML, load the proxy.html page of the same domain,
  4. This time can pass the iframe. ContentWindow. Name access b.h HTML content of the name.
/ / a.html:http://www.demo1.com/a.html
var proxy = function(url, callback) {
    var state = 0;
    var iframe = document.createElement('iframe');
    // Load the cross-domain page
    iframe.src = url;
    // The onload event fires twice, the first time the cross-domain page is loaded and the data is stored in window.name
    iframe.onload = function() {
        if (state === 1) {
            // After the second onload(syndomain proxy page) succeeds, the data in syndomain window.name is read
            callback(iframe.contentWindow.name);
        } else if (state === 0) {
            // After the first onload succeeds, switch to the same-domain proxy page
            iframe.contentWindow.location = 'http://www.demo1.com/proxy.html';
            state = 1; }};document.body.appendChild(iframe);
};
// Request cross-domain B page data
proxy('http://www.demo2.com/b.html'.function(data){
    alert(data);
});

/ / poxy. HTML: http://www.demo1.com/proxy.html
// proxy page with empty content in the same domain as b

/ / b.h HTML: http://www.demo2.com/b.html
<script>
    window.name = 'xxxx';
</script> 

Copy the code