Understand: front end cross domain problems JS solving cross domain problems VUE agent solving cross domain problems principle

What is cross domain

Cross domain: a document or script in one domain attempts to request resources in another domain

The broad cross domain includes the following contents:

1. Resource jump (link jump, redirect jump, form submission)
2. Resource request (internal reference, script, picture img, frame)
3.script internal requests (ajax, dom requests, and js cross domain calls

Cross domain issues arise:

Only the browser side appears, directly using the terminal request, there will be no cross domain interception, which belongs to the browser side security policy. The browser intercepts requests of different origins, limiting cross domain resource access

What is homology

Same origin policy: the same origin policy. If two resources (pages), "Protocol", "domain name" and "port" are the same, they are the same origin.

Even if two different domain names point to the same ip, they are not homologous

What are the limitations of non homology (cross domain)

*cookie, localstorage, indexDB cannot read
 *Dom and JS objects cannot interoperate
 *Ajax request cannot be sent

Common cross domain demo

URL                                      explain                    Allow communication or not
http://www.domain.com/a.js
http://www.domain.com/b.js          The same domain name, different files or paths allow
http://www.domain.com/lab/c.js

http://www.domain.com:8000/a.js
http://www.domain.com/b.js          The same domain name, different ports are not allowed
 
http://www.domain.com/a.js
https://www.domain.com/b.js         The same domain name, different protocols do not allow
 
http://www.domain.com/a.js
http://192.168.4.12/b.js domain name and domain name corresponding to the same ip are not allowed
 
http://www.domain.com/a.js
http://x.domain.com/b.js same primary domain, different subdomains are not allowed
http://domain.com/c.js
 
http://www.domain1.com/a.js
http://www.domain2.com/b.js         Different domain names are not allowed

Front end solution to cross domain

  • JSONP

    • Principle: in a page, if js wants to access the data of another non homologous domain, it is limited by the browser, but when the browser parses and loads the script tag, it allows one page to load the js tags of multiple domains, and the js tag is actually similar to a get request, but the returned data is a script object in JSON format.
    • Usage: encapsulate the get request into the script tag, use the script tag to make the get request, and finally parse the script tag data
    • code:
      var  script = document.createElement('script')
      script.style = 'text/javascript'
    
      //Pass the get address to be requested to the src attribute of script, and add a callback function
      script.setAttribute('scr','http://www.domain2.com:8080/login?user=admin&callback=handleCallback')
      //Put script tags in the document
      document.head.appendChild(script)
      //Execute callback function
      function handleCallback(res){
          //Processing JSON format data
          alert(JSON.stringify(res))
      }
      
    
    • Because the request script can only be a get method, JSONP can only solve the get request, but post or other http methods cannot
  • Cross domain resource sharing

    • Principle:
      • cors: cross origin - resource sharing allows browsers to send http requests to cross source servers. Both browsers and servers need to support it at the same time
      • When the browser makes a cross domain request: 1. The simple request directly carries the origin information in the header information to identify which source it belongs to, and the server configures access control allow origin to accept which domain name cross domain access, which can be * allow all
      • If it is a non simple request, it will send a pre inspection request before the formal request
    • In short (simple request):
      • It is a means of two terminal cooperation to allow cross domain resource limitation of clock in
      • Browser side: request header carries origin information
      • Server: configure access control allow origin to allow cross domain sources
    • code:
      • Native: xmlHttpRequest does not need to configure the request header, and the simple request will automatically bring the origin attribute
        var xhr = new XMLHttpRequest(); // IE8/9 required window.XDomainRequest compatible
        
        
            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);
                }
            };
        
        
      • AJAX: there is a property crossDomain. If it is configured as true, the request header will carry the org cross domain extra information, but will not automatically contain cookie s
        $.ajax({
            ...
        xhrFields: {
            withCredentials: true    // Whether the front-end settings have cookie s
        },
        crossDomain: true,   // The request header will contain additional information across domains, but will not contain cookie s
            ...
        });
        
      • axios in VUE also places origin in the request header by default. No additional configuration is required
    • Server configuration
        /*
         * Import package: import javax.servlet.http.HttpServletResponse;
         * Defined in the interface parameter: HttpServletResponse response
         */
      
        // Domain name that allows cross domain access: if there is a port, write all (protocol + domain name + port). If there is no port, do not add '/'at the end
        response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com"); 
      
        // Allow cookie s with authentication on the front end: after this option is enabled, the domain name above cannot be '*', you must specify a specific domain name, otherwise the browser will prompt
        response.setHeader("Access-Control-Allow-Credentials", "true"); 
      
        // Two common custom headers that need to be set at the back end when prompted for OPTIONS pre check
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
      
      
  • Reverse agent (NodeJs middleware agent cross domain) (Vue agent cross domain) (nginx forwarding agent)

    • Scenario: when the server cannot modify the CORS and the client is all complicated to change to JSON mode, you can only use the intermediate proxy server to set the proxy server to support CORS or the proxy server is the same as the request page, so that the page can directly request the proxy server. When the proxy server performs interface proxy, the proxy requests the target interface address and returns data

    • Principle: cross domain restriction is only the browser side security policy, not the inherent restriction of http protocol, so the intermediate server can request the target server normally when the parameters and cookie s are valid. The configuration of proxy in Vue (node + webback + webback dev server) is to start a homologous service for interface proxy

    • be careful:

      • 1. When a non vue, webpack, dev serve service, nginx or node express service is used as a reverse proxy, it is usually not the same origin as the page, and there is also a cross domain problem in accessing the proxy server from a different origin. You need to configure cors to allow cross domain access and access control allow header
      • In the webpack dev server service, by default, it should be basically the same source as the test environment page, and there is no need to configure the request header to allow
    • code:

      • Webpack dev server agent
              module.exports = {
              entry: {},
              module: {},
              ...
              devServer: {
                  historyApiFallback: true,
                  proxy: [{
                      context: '/login',
                      target: 'http://www.domain2.com:8080 ', / / agent cross domain target interface
                      changeOrigin: true,
                      secure: false,  // Use when some https services report errors
                      cookieDomainRewrite: 'www.domain1.com'  // It can be false, indicating no modification
                  }],
                  noInfo: true
              }
          }
      
      • node express reverse agent
      var express = require('express');
      var proxy = require('http-proxy-middleware');
      var app = express();
      
      app.use('/', proxy({
          // Agent cross domain target interface
          target: 'http://www.domain2.com:8080',
          changeOrigin: true,
      
          // Modify response header information, realize cross domain and allow cookie
          onProxyRes: function(proxyRes, req, res) {
              res.header('Access-Control-Allow-Origin', 'http://www.domain1.com');
              res.header('Access-Control-Allow-Credentials', 'true');
          },
      
          // Modify cookie domain name in response information
          cookieDomainRewrite: 'www.domain1.com'  // It can be false, indicating no modification
      }));
      
      app.listen(3000);
      console.log('Proxy server is listen at port 3000...');
      
      • nginx forwarding agent
          #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 restriction of homology. The following cross domain configuration can not be enabled
                  add_header Access-Control-Allow-Origin http://www.domain1.com;   #When the current end only cross domains without cookie s, it can be*
                  add_header Access-Control-Allow-Credentials true;
              }
          }
      
  • Other js HACK methods

    • Different scenes in the same subdomain of the main domain: docment.domain+iframe

    • Three pages cross domains: location.hash + iframe

    • window.name + iframe

    • H5 new postMessage (cross window message interworking method)

    • About iframe:

      • In fact, it is equivalent to opening a new sub page under the current page. Follow all page to page resource access principles, such as
        • 1. When the main page and iframe page are different from each other, the DOM cannot be accessed
        • 2. When the primary domain is the same, the secondary domain names are different, document.domain Can circumvent the same origin policy, and can access the DOM with each other
    • location.hash:

      • The time page fragment identifier at the end of the url is used to indicate which part of the page information is rendered by the browser, but the page will not refresh after changing this value. After setting, all pages can access the location information of the window through the document object, which can realize smart cross domain
      • code:
          //The parent window can write information to the fragment identifier of the child window.
      
          var src = originURL + '#' + data;
          document.getElementById('myIFrame').src = src;
      
          //Child windows are notified by listening for hashchange events.
      
          window.onhashchange = checkMessage;
      
          function checkMessage() {
          var message = window.location.hash;
          // ...
          }
      
    • Similarly, window.name It is also a cross domain way of hack method

      • The browser window has window.name Property. The biggest feature of this property is that no matter whether it is homologous or not, as long as the property is set in the same window by the previous page, the latter page can read it.

        The parent window first opens a child window and loads a page of different origin, which writes the information window.name Property.

        window.name = data;

        Next, the child window jumps back to a web address in the same domain as the main window.

        location = 'http://parent.url.com/xxx.html';

        The main window can then read the window.name Yes.

        var data = document.getElementById('myFrame').contentWindow.name;

        The advantage of this approach is that, window.name It has a large capacity and can put very long strings; the disadvantage is that it has to listen to subwindows window.name Property changes affect the performance of web pages.

    • postMessage

      • window.name and location.hash All of them belong to the ingenious way. They use the non data property of browser page or the inherent property of window to achieve the purpose of cross page. But in H5, the postMessage API is added to realize cross tab and cross window data communication and allow window communication, regardless of whether they are of the same origin or not

Summary:

In common use, there are three ways: agent, CORS, or JSONP. The prohibition of cross domain is a kind of browser security policy. Although there are certain restrictions on the hands and feet of developers, in some special websites or websites with high security requirements, network security cannot be ignored

Thank you very much: the following article has given me a lot of help. Thank you for your hard work. You can click to see more information

Front end common solutions to cross domain problems

9 common cross domain solutions

Front end cross domain issues

Tags: JSON Vue Webpack Nginx

Posted on Wed, 20 May 2020 03:27:59 -0700 by lavender