Cross domain

Because browsers have the same origin policy for security reasons, any difference in protocol, domain name, or port is treated as a different domain. That is, if a protocol, domain name, or port difference is cross-domain, the Ajax request will fail.

The solution

jsonp

The principle behind JSONP is simply to exploit the vulnerability that script tags have no cross-domain limitations. The script tag points to an address that needs to be accessed and provides a callback function to receive data when it needs to communicate.

<script src="http://domain/api? param1=a&param2=b&callback=jsonp"></script>
<script>
    function jsonp(data) {
    	console.log(data)
	}
</script>
Copy the code

The copy code JSONP is simple to use and compatible, but is limited to GET requests. In development, you may encounter multiple JSONP requests with the same callback function name. In this case, you need to wrap a JSONP

function jsonp(url, jsonpCallback, success) {
  let script = document.createElement('script')
  script.src = url
  script.async = true
  script.type = 'text/javascript'
  window[jsonpCallback] = function(data) {
    success && success(data)
  }
  document.body.appendChild(script)
}
jsonp('http://xxx'.'callback'.function(value) {
  console.log(value)
})
Copy the code

CORS

Cross-origin ResourceSharing (CORS) defines how browsers and servers communicate when accessing cross-domain resources.

The basic idea behind CORS is to use custom HTTP headers to let the browser communicate with the server to determine whether a request or response should succeed or fail. Currently, all browsers support this function, and Internet Explorer cannot be lower than Internet Explorer 10.

Because you need to do it through XDomainRequest.

The entire CORS communication process is completed automatically by the browser without user participation. For developers, CORS communication is no different from same-origin AJAX communication, and the code is exactly the same. As soon as the browser discovers that an AJAX request crosses the source, it automatically adds some additional headers, and sometimes an additional request, but the user doesn’t feel it.

Therefore, the key to CORS communication is the server. As long as the server implements the CORS interface, cross-source communication is possible.

Server support for CORS is mainly through setting access-Control-Allow-Origin. This attribute indicates which domain names can access resources. If a wildcard is set, all websites can access resources. If the browser detects the Settings, Ajax can be allowed to access across domains.

postMessage

This is the API that comes out of H5 and is supported above IE8. The window.postMessage() method can safely implement cross-source communication.

In general, scripts with two different pages can only communicate with each other if the page executing them is on the same protocol (usually HTTPS), port number (443 is the default value for HTTPS), and host (the module document.domain of the two pages is set to the same value). The window.postmessage () method provides a controlled mechanism to circumvent this limitation and is safe as long as it is used correctly.

When the window.postMessage() method is called, a MessageEvent message is sent to the target window after all page scripts have been executed.

The MessageEvent message has four properties to note:

  • The message attribute indicates the type of the message;

  • The data attribute is the first argument to window.postMessage;

  • The origin property represents the current state of the page when the window.postmessage () method is called;

  • The source property records information about the window in which the window.postMessage() method is called.

grammar

otherWindow.postMessage(message, targetOrigin);

OtherWindow: Specifies the target window, that is, the window to which the message is sent, either as a member of the window.frames property or as a window created by the window.open method

Message: indicates the message to be sent. The type of the message is String or Object (Not supported by Internet Explorer 8 and 9).

TargetOrigin: is to limit the range of messages to be received

Example: A page sends A message using the postMessage method:

window.onload = function() {  
    var ifr = document.getElementById('ifr');  
    var targetOrigin = "http://www.google.com";  
    ifr.contentWindow.postMessage('hello world! ', targetOrigin);  
};
Copy the code

Page B listens for and receives messages via message events:

var onmessage = function(event) { var data = event.data; Var origin = event.origin; // Message source address varsource= event.source; // Source Window objectif(origin=="http://www.baidu.com"){  
console.log(data);//hello world!  
  }  
};  
if(typeof window.addEventListener ! ='undefined') {  
  window.addEventListener('message', onmessage, false);  
} else if(typeof window.attachEvent ! ='undefined'{/ /for ie  
  window.attachEvent('onmessage', onmessage);  
}
Copy the code

Nginx agents cross domains

Cross-domain principle: The same Origin policy is a security policy of the browser, not a part of the HTTP protocol. The server invokes the HTTP interface only using THE HTTP protocol, and does not execute JS scripts. There is no need for the same origin policy, so there is no crossing problem.

Nginx configure a proxy server (domain name and domain1 the same, different port) as a jumper, reverse proxy access to domain2 interface, and can incidentally modify the cookie in the domain information, convenient for the current domain cookie writing, cross-domain login.

Nginx configuration:

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; # change the domain name in cookie
        index  index.html index.htm;

        # When accessing Nignx using middleware proxy interfaces such as Webpack-dev-server, there is no browser participation, so there is no source restriction, the following cross-domain configuration can not be enabled
        add_header Access-Control-Allow-Origin http://www.domain1.com;  # If the current end is cross-domain only without cookies, the value can be *
        add_header Access-Control-Allow-Credentials true; }}Copy the code

WebSocket and NodeJs middleware cross domain and other methods

None of these methods are used very much except nodeJS, and websockets are not used specifically for cross-domain purposes, but for notifications, chat, etc.

By shotCat Link: juejin.cn/post/684490… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.