9 common front-end cross domain solutions

Posted by jomofee on Sat, 25 Dec 2021 08:47:44 +0100

9 common front-end cross domain solutions (detailed explanation)

2019.09. 02 21:54 - 73879 browse

1, What is cross domain?

   in the front-end field, cross domain refers to that the browser allows to send cross domain requests to the server, so as to overcome the limitation that Ajax can only be used in the same source.

What is homology strategy?

   homology policy is an agreement. The browser was introduced by Netscape in 1995. It is the most core and basic security function of the browser. Without homology policy, the browser is vulnerable to XSS, CSFR and other attacks. The so-called homology means that "protocol + domain name + port" are the same. Even if two different domain names point to the same ip address, they are not homologous.

  the same origin policy limits the following behaviors:

  • Cookie s, LocalStorage, and IndexDB cannot be read
  • DOM and JS objects cannot be obtained
  • AJAX request cannot be sent

2, Common cross domain scenarios

URLexplainAllow communication
http://www.domain.com/a.js
http://www.domain.com/b.js
http://www.domain.com/lab/c.js
Same domain name, different files or pathsallow
http://www.domain.com:8000/a.js
http://www.domain.com/b.js
Same domain name, different portsnot allow
http://www.domain.com/a.js
https://www.domain.com/b.js
Same domain name, different protocolsnot allow
http://www.domain.com/a.js
http://192.168.4.12/b.js
Domain name and domain name correspond to the same ip addressnot allow
http://www.domain.com/a.js
http://x.domain.com/b.js
http://domain.com/c.js
The primary domain is the same, but the sub domains are differentnot allow
http://www.domain1.com/a.js
http://www.domain2.com/b.js
Different domain namesnot allow

3, 9 cross domain solutions

1. JSONP cross domain

   the principle of jsonp is to use the < script > tag without cross domain restrictions and send a GET request with callback parameters through the src attribute of the < script > tag. The server pieced the interface return data into the callback function and returned it to the browser. The browser parsed and executed it, so that the front end can GET the data returned by the callback function.

1) Native JS implementation:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code> <script>
    var script = document.createElement('script');
    script.type = 'text/javascript';

    // Pass a callback function name to the back end to facilitate the execution of the callback function defined in the front end when the back end returns
    script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
    document.head.appendChild(script);

    // Callback execution function
    function handleCallback(res) {
        alert(JSON.stringify(res));
    }
 </script>
</code></span></span></span></span></span></span>

The server returns the following (the global function is executed when it returns):

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>handleCallback({"success": true, "user": "admin"})
</code></span></span></span></span></span></span>

2) jquery Ajax implementation:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>$.ajax({
    url: 'http://www.domain2.com:8080/login',
    type: 'get',
    dataType: 'jsonp',  // The request method is jsonp
    jsonpCallback: "handleCallback",  // Custom callback function name
    data: {}
});
</code></span></span></span></span></span></span>

3) Vue axios implementation:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>this.$http = axios;
this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) => {
    console.log(res); 
})
</code></span></span></span></span></span></span>

Backend node JS code:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>var querystring = require('querystring');
var http = require('http');
var server = http.createServer();

server.on('request', function(req, res) {
    var params = querystring.parse(req.url.split('?')[1]);
    var fn = params.callback;

    // jsonp return settings
    res.writeHead(200, { 'Content-Type': 'text/javascript' });
    res.write(fn + '(' + JSON.stringify(params) + ')');

    res.end();
});

server.listen('8080');
console.log('Server is running at port 8080...');
</code></span></span></span></span></span></span>

The disadvantage of jsonp: only one request can be sent.

2. Cross domain resource sharing (CORS)

   CORS is a W3C standard, and its full name is "cross origin resource sharing".
It allows browsers to issue XMLHttpRequest requests to cross source servers, thus overcoming the limitation that AJAX can only be used from the same source.
CORS requires both browser and server support. At present, all browsers support this function, and IE browser cannot be lower than IE10.

  the browser divides CORS cross domain requests into simple requests and non simple requests.

  as long as the following two conditions are met at the same time, it is a simple request

(1) Use one of the following methods:

  • head
  • get
  • post

(2) The requested Heder is

  • Accept
  • Accept-Language
  • Content-Language
  • Content type: limited to three values: application/x-www-form-urlencoded, multipart / form data, and text/plain

If the above two conditions are not met at the same time, it is a non simple request. The browser handles these two types differently.

Simple request

  for simple requests, the browser directly sends CORS requests. Specifically, add an Origin field to the header information.

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>GET /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
</code></span></span></span></span></span></span>

   in the header information above, the Origin field is used to indicate which source (protocol + domain name + port) the request comes from. The server decides whether to agree to the request according to this value.

The response header fields of CORS request settings start with access control -:

1) Access control allow origin: required

    its value is either the value of the Origin field at the time of the request, or a *, indicating that the request for any domain name is accepted.

2) Access control allow credentials: optional

   its value is a Boolean value indicating whether cookies are allowed to be sent. By default, cookies are not included in CORS requests. If it is set to true, it means that the server has explicit permission. Cookie s can be included in the request and sent to the server together. This value can only be set to true. If the server does not want the browser to send cookies, delete this field.

3) Access control expose headers: optional

   during CORS request, the getResponseHeader() method of XMLHttpRequest object can only get six basic fields: cache control, content language, content type, Expires, last modified and Pragma. If you want to get other fields, you must specify them in access control expose headers. The above example specifies that getresponseheader ('FooBar ') can return the value of the FooBar field.

Non simple request

    non simple requests are those that have special requirements for the server, such as the request method is PUT or DELETE, or the type of content type field is application/json. For CORS requests that are not simple requests, an HTTP query request will be added before formal communication, which is called "preflight".

Pre inspection request

   the request method used for the "pre check" request is OPTIONS, indicating that the request is used for inquiry. In the request header information, the key field is Origin, indicating which source the request comes from. In addition to the Origin field, the header information of the "pre check" request includes two special fields.

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0..
</code></span></span></span></span></span></span>

1) Access control request method: required

  it is used to list the HTTP methods used in the browser's CORS request. The above example is PUT.

2) Access control request headers: optional

    this field is a comma separated string that specifies the header information field that the browser CORS request will send additionally. The above example is x-custom header.

Response to pre inspection request

  after receiving the "pre check" request, the server checks the Origin, access control request method and access control request headers fields, confirms that cross source requests are allowed, and can respond.

  in the HTTP response, except for the access control allow origin field, other CORS related fields are as follows:

1) Access control allow methods: required

  its value is a comma separated string indicating all cross domain request methods supported by the server. Note that all supported methods are returned, not just the one requested by the browser. This is to avoid multiple "pre check" requests.

2)Access-Control-Allow-Headers

  if the browser request includes the access control request headers field, the access control allow headers field is required. It is also a comma separated string, indicating all header information fields supported by the server, not limited to the fields requested by the browser in "pre check".

3) Access control allow credentials: optional

  the meaning of this field is the same as that of simple request.

4) Access control Max age: optional

   used to specify the validity period of this pre inspection request, in seconds.

CORS cross domain example

1) Front end settings:

  • Native ajax:
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#C1e6c6 "> < code > var XHR = new xmlhttprequest(); / / IE8 / 9 should be compatible with window.XDomainRequest

// Front end setting whether to bring cookie s
xhr.withCredentials = true;

xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};
</code></span></span></span></span></span></span>
  • jquery ajax:
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>$.ajax({
    ...
   xhrFields: {
       withCredentials: true    // Front end setting whether to bring cookie s
   },
   crossDomain: true,   // It will make the request header contain additional information across domains, but will not contain cookie s
    ...
});
</code></span></span></span></span></span></span>

2) Server settings:

  • nodejs code
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>var http = require('http');
var server = http.createServer();
var qs = require('querystring');

server.on('request', function(req, res) {
    var postData = '';

    // Data block receiving
    req.addListener('data', function(chunk) {
        postData += chunk;
    });

    // Data received
    req.addListener('end', function() {
        postData = qs.parse(postData);

        // Cross domain background settings
        res.writeHead(200, {
            'Access-Control-Allow-Credentials': 'true',     // The backend allows sending cookies
            'Access-Control-Allow-Origin': 'http://www.domain1.com ', / / allowed domains (protocol + domain name + port)
            /* 
             * The cookie set here is still domain 2, not domain 1, because the backend cannot write cookies across domains (nginx reverse proxy can be implemented),
             * However, as long as the cookie authentication is written once in domain2, the following cross domain interfaces can obtain cookies from domain2, so that all interfaces can be accessed across domains
             */
            'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly'  // HttpOnly is used to make js unable to read cookie s
        });

        res.write(JSON.stringify(postData));
        res.end();
    });
});

server.listen('8080');
console.log('Server is running at port 8080...');
</code></span></span></span></span></span></span>

3. nginx proxy cross domain

   nginx proxy cross domain is essentially the same as CORS cross domain principle. It sets the fields such as access control allow origin... In the request response header through the configuration file.

1) nginx configuration solves iconfont cross domain

  the browser's cross domain access to js, css, img and other conventional static resources is permitted by the same origin policy, with the exception of iconfont font file (eot|otf|ttf|woff|svg). At this time, the following configuration can be added to the static resource server of nginx.

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>location / {
  add_header Access-Control-Allow-Origin *;
}
</code></span></span></span></span></span></span>

2) nginx reverse proxy interface Cross Domain

Cross domain problem: the same origin policy is only a security policy for browsers. When the server calls the HTTP interface, it only uses the HTTP protocol, does not need the homology policy, and there is no cross domain problem.

Implementation idea: configure a proxy server through Nginx (the domain name is the same as domain1 and the port is different) as a springboard machine. The reverse proxy accesses the domain2 interface, and can modify the domain information in the cookie to facilitate the writing of the current domain cookie and realize cross domain access.

Specific configuration of nginx:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>#proxy server
server {
    listen       81;
    server_name  www.domain1.com;

    location / {
        proxy_pass   http://www.domain2.com:8080;  # Reverse proxy
        proxy_cookie_domain www.domain2.com www.domain1.com; #Modify the domain name in the cookie
        index  index.html index.htm;

        # When using middleware proxy interfaces such as webpack dev server to access nignx, there is no browser participation at this time, so there is no homology restriction. The following cross domain configuration can not be enabled
        add_header Access-Control-Allow-Origin http://www.domain1.com;  # When the current end only spans domains without cookie s, it can be*
        add_header Access-Control-Allow-Credentials true;
    }
}
</code></span></span></span></span></span></span>

4. nodejs middleware agent cross domain

   node middleware implements cross domain proxy. The principle is roughly the same as nginx. It realizes data forwarding by starting a proxy server. It can also modify the domain name in the cookie in the response header by setting the cookie domainrewrite parameter to write the cookie in the current domain to facilitate interface login authentication.

1) Cross domain of non vue framework

  use node + Express + HTTP proxy middleware to build a proxy server.

  • Front end code:
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>var xhr = new XMLHttpRequest();

// Front end switch: whether the browser reads or writes cookie s
xhr.withCredentials = true;

// Access HTTP proxy middleware proxy server
xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true);
xhr.send();
</code></span></span></span></span></span></span>
  • Middleware server code:
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>var express = require('express');
var proxy = require('http-proxy-middleware');
var app = express();

app.use('/', proxy({
    // Proxy cross domain target interface
    target: 'http://www.domain2.com:8080',
    changeOrigin: true,

    // Modify the response header information to achieve cross domain and allow cookie s
    onProxyRes: function(proxyRes, req, res) {
        res.header('Access-Control-Allow-Origin', 'http://www.domain1.com');
        res.header('Access-Control-Allow-Credentials', 'true');
    },

    // Modify the cookie domain name in the response information
    cookieDomainRewrite: 'www.domain1.com'  // It can be false, indicating that it is not modified
}));

app.listen(3000);
console.log('Proxy server is listen at port 3000...');

</code></span></span></span></span></span></span>

2) Cross domain of vue framework

  for the project built by node + vue + webpack + webpack dev server, request the interface across domains and modify the webpack directly config. JS configuration. In the development environment, vue rendering service and interface proxy service are the same as webpack dev server, so there is no cross domain between page and proxy interface.

webpack.config.js part configuration:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>module.exports = {
    entry: {},
    module: {},
    ...
    devServer: {
        historyApiFallback: true,
        proxy: [{
            context: '/login',
            target: 'http://www.domain2.com:8080 ', / / proxy cross domain target interface
            changeOrigin: true,
            secure: false,  // Used when the proxy reports an error for some https services
            cookieDomainRewrite: 'www.domain1.com'  // It can be false, indicating that it is not modified
        }],
        noInfo: true
    }
}
</code></span></span></span></span></span></span>

5,document.domain + iframe cross domain

  this scheme is limited to cross domain application scenarios with the same primary domain and different sub domains. Implementation principle: both pages are forced to set document. XML through js Domain as the basic primary domain, the same domain is realized.

1) Parent window:( http://www.domain.com/a.html)

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
    document.domain = 'domain.com';
    var user = 'admin';
</script>
</code></span></span></span></span></span></span>

1) Child window:( http://child.domain.com/a.html)

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><script>
    document.domain = 'domain.com';
    // Gets the variable in the parent window
    console.log('get js data from parent ---> ' + window.parent.user);
</script>
</code></span></span></span></span></span></span>

6,location.hash + iframe cross domain

   implementation principle: if a wants to communicate with b across domains, it is realized through the middle page c. Three pages, using iframe location between different domains Hash value transfer, direct js access between the same fields to communicate.

   specific implementation: domain a: a.html - > domain B: b.html - > domain a: c.html. Different domains a and B can only communicate one way through hash value, and different domains B and C can only communicate one way, but C and a are in the same domain, so C can communicate through parent Parent accesses all objects on the a page.

1)a.html: (http://www.domain1.com/a.html)

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');

    // Pass hash value to b.html
    setTimeout(function() {
        iframe.src = iframe.src + '#user=admin';
    }, 1000);
    
    // Callback methods open to c.html in the same domain
    function onCallback(res) {
        alert('data from c.html ---> ' + res);
    }
</script>
</code></span></span></span></span></span></span>
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');

    // Listen for the hash value from a.html and then pass it to c.html
    window.onhashchange = function () {
        iframe.src = iframe.src + location.hash;
    };
</script>
</code></span></span></span></span></span></span>
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><script>
    // Listen for the hash value from b.html
    window.onhashchange = function () {
        // Then, the result is returned by operating the js callback of a.html in the same domain
        window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
    };
</script>
</code></span></span></span></span></span></span>

7,window.name + iframe cross domain

  window. The uniqueness of the name attribute: the name value still exists after different pages (even different domain names) are loaded, and can support a very long name value (2MB).

1)a.html: (http://www.domain1.com/a.html)

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>var proxy = function(url, callback) {
    var state = 0;
    var iframe = document.createElement('iframe');

    // Load cross domain pages
    iframe.src = url;

    // The onload event will be triggered twice. The cross domain page will be loaded for the first time and the data will be saved in the window name
    iframe.onload = function() {
        if (state === 1) {
            // After the second onload (same domain proxy page) succeeds, read the same domain window Data in name
            callback(iframe.contentWindow.name);
            destoryFrame();

        } else if (state === 0) {
            // After the first onload (cross domain page) is successful, switch to the same domain proxy page
            iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';
            state = 1;
        }
    };

    document.body.appendChild(iframe);

    // After obtaining the data, destroy the iframe to free the memory; This also ensures security (not accessed by frame js in other domains)
    function destoryFrame() {
        iframe.contentWindow.document.write('');
        iframe.contentWindow.close();
        document.body.removeChild(iframe);
    }
};

// Request cross domain b page data
proxy('http://www.domain2.com/b.html', function(data){
    alert(data);
});
</code></span></span></span></span></span></span>

2)proxy.html: (http://www.domain1.com/proxy.html)

   the intermediate agent page has the same domain as a.html, and the content can be empty.

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><script>
    window.name = 'This is domain2 data!';
</script>
</code></span></span></span></span></span></span>

  through the src attribute of iframe, the external domain is transferred to the local domain, and the cross domain data is transferred from the window of iframe Name is passed from the foreign domain to the local region. This skilfully bypasses the browser's cross domain access restrictions, but at the same time, it is a secure operation.

8. postMessage cross domain

  postMessage is an API in HTML5 XMLHttpRequest Level 2 and one of the few window attributes that can operate across domains. It can be used to solve the following problems:

  • Data transfer between a page and a new window it opens
  • Message passing between multiple windows
  • Page and nested iframe messaging
  • Cross domain data transfer in the above three scenarios

Usage: the postMessage(data,origin) method accepts two parameters:

  • data: the html5 specification supports any basic type or replicable object, but some browsers only support strings, so it's best to use JSON when passing parameters Stringify() serialization.
  • origin: Protocol + host + port number, which can also be set to "*", indicating that it can be passed to any window. If you want to specify the same source as the current window, set it to "/.
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
        var data = {
            name: 'aym'
        };
        // Transfer cross domain data to domain2
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
    };

    // Accept the data returned by domain2
    window.addEventListener('message', function(e) {
        alert('data from domain2 ---> ' + e.data);
    }, false);
</script>
</code></span></span></span></span></span></span>
<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><script>
    // Receive data from domain1
    window.addEventListener('message', function(e) {
        alert('data from domain1 ---> ' + e.data);

        var data = JSON.parse(e.data);
        if (data) {
            data.number = 16;

            // Send it back to domain1 after processing
            window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
        }
    }, false);
</script>
</code></span></span></span></span></span></span>

9. WebSocket protocol cross domain

WebSocket protocol is a new protocol of HTML5. It realizes full duplex communication between browser and server, and allows cross domain communication. It is a good implementation of server push technology.
The native WebSocket API is inconvenient to use. We use socket IO, which well encapsulates the webSocket interface, provides a simpler and more flexible interface, and provides downward compatibility for browsers that do not support WebSockets.

1) Front end code:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code><div>user input: <input type="text"></div>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<script>
var socket = io('http://www.domain2.com:8080');

// Connection successfully processed
socket.on('connect', function() {
    // Listen for server messages
    socket.on('message', function(msg) {
        console.log('data from server: ---> ' + msg); 
    });

    // Monitor server shutdown
    socket.on('disconnect', function() { 
        console.log('Server socket has closed.'); 
    });
});

document.getElementsByTagName('input')[0].onblur = function() {
    socket.send(this.value);
};
</script>
</code></span></span></span></span></span></span>

2) Nodejs socket background:

<span style="color:#1c1f21"><span style="color:#1c1f21"><span style="color:#1c1f21"><span style="background-color:#c1e6c6"><span style="color:#333333"><span style="background-color:#c1e6c6"><code>var http = require('http');
var socket = require('socket.io');

// Enable http service
var server = http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-type': 'text/html'
    });
    res.end();
});

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

// Listen for socket connections
socket.listen(server).on('connection', function(client) {
    // Receive information
    client.on('message', function(msg) {
        client.send('hello: ' + msg);
        console.log('data from client: ---> ' + msg);
    });

    // Disconnect processing
    client.on('disconnect', function() {
        console.log('Client socket has closed.'); 
    });
});
</code></span></span></span></span></span></span>

Summary

  the above are nine common cross domain solutions, jsonp (only supports get requests and old IE browsers) is suitable for loading static resources such as js, css and img of different domain names; CORS (all types of HTTP requests are supported, but not for browsers below IE10). It is suitable for ajax cross domain requests. The cross domain principle of Nginx proxy is similar to that of nodejs middleware. They both build a server and directly request HTTP interfaces on the server side, which is suitable for front-end projects separated from the front-end and back-end interfaces. document.domain+iframe is suitable for the same primary domain name and different subdomains Same cross domain request. postMessage and websocket are new features of HTML5. They are not very compatible. They are only applicable to mainstream browsers and IE10 +.

   there are so many cross domain schemes, there is no best, only the most appropriate. Select the cross domain scheme according to the specific use scenario. I hope this blog can give you some help~~