Cross-domain solution introduction 2, transferred from github.

Cross-domain solution introduction 2, transferred from github.

Cross-domain issues

The cornerstone of browser security is the "same-origin policy." The so-called homologous refers to the same protocol, the same domain name, and the same port. As long as one of them is different, it is called a different source. Websites from different sources cannot request data from each other to ensure the security of user data. But sometimes, a website has to request data from other domains. This process is called cross-domain.

There are several ways to implement cross-domain:

(1) JSONP

The principle of JSONP (JSON with padding) is that the script tag is not restricted by the same-origin security policy, and it can send get requests to other domains.

function handleResponse(data) {
	console.log('The response data is:' + data);
}
//Add script tags dynamically
var script = document.createElement('script');
script.src ='http://www.baidu.com/json?callback=handleResponse';
script.setAttribute('type','text/javascript');
document.body.appendChild(script);

After receiving the get request in the background, it generates the corresponding JSONP data handleResponse({'data': serverdata}) according to the callback parameters  . This piece of data is returned to the front end and executed as js code, triggering the callback function.

jQuery and JSONP

$(document).ready(function(){
	$.ajax({
		type:'get',
		async: false,
		//Query the information of CA1998 flight
		url:'http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998',
		dataType:'jsonp',
		//Passed to the request handler or page to obtain the parameter name of the jsonp callback function name (generally default: callback)
		jsonp:'callback',
		//Customized jsonp callback function name, the default is the random function name automatically generated by jQuery, you can also write "?", jQuery will automatically process the data for you
		jsonpCallback:'flightHandler',
		success: (json) => {
			alrt('The flight information you found: fare: '+ json.price +' yuan, remaining tickets: '+ json.tickets +' tickets.');
		},
		error: () => {
			alrt('fail');
		}
	});
});

(2) CORS

CORS is a W3C standard, the full name is cross-origin resource sharing, which allows browsers to send XMLHttpRequest requests to cross-origin servers, thus overcoming the restriction that AJAX can only be used from the same source.

The entire CORS communication process is automatically completed by the browser, and the user does not need to participate. For front-end developers, the codes of the same source Ajax and CORS are exactly the same. Therefore, the key to implementing CORS is whether the server provides a CORS interface.

Simple request example:

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...

If the server allows cross-domain requests from http://api.bob.com, it will respond as follows:

Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Credentials: true//whether to allow cookies to be sent
Access-Control-Expose-Headers: FooBar//additional header field
Content-Type: text/html; charset=utf-8

If it is not allowed, the Access-Control-Allow-Origin field will not be set. If the server sets this field to *, it means that the server accepts cross-domain requests from all domains.

Access-Control-Allow-Credentials: true means that the server accepts cookies, and the developer should open the withCredentials property in AJAX to allow the browser to send cookies:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

Cross-domain resource sharing CORS detailed explanation

(3) iframe + HTML5 postMessage

That is to say , cross-domain communication is carried out between different windows through the HTML5 API  postMessage , and the format is:

otherWindow.postMessage(data, targetOrigin);
//otherWindow refers to the window to receive the message, targetOrigin limits the domain of the receiving window, if you don’t want to limit it, just set it as *

Example:

<!--a.com/index.html-->
<iframe id="ifr" src="b.com/index.html"></iframe>
<script type="text/javascript">
window.onload = function() {
    var ifr = document.getElementById('ifr');
    var targetOrigin ='http://b.com';//The effect is the same if written as'http://b.com/c/proxy.html'
                                       //If it is written as'http://c.com', postMessage will not be executed
    ifr.contentWindow.postMessage('Message from a.com!', targetOrigin);
};
</script>
<!--b.com/index.html-->
<script type="text/javascript">
    window.addEventListener('message', function(event){
       //Determine the source address of the message by the origin attribute
        if (event.origin =='http://a.com') {
            alrt(event.data);//"Message from a.com!" pops up
            alrt(event.source);//Reference to the window object in a.com and index.html
                                 //But due to the same-origin policy, event.source cannot access the window object here
        }
    }, false);
</script>

(4) iframe + window.name

Principle: The value of windoe.name still exists after different pages (even different domain names) are loaded, and can support very long name values ​​(2MB)

a.com/1.html

<script type="text/javascript">
function getData() {
	var ifr = document.getElementById('proxy');
	ifr.src ='a.com/2.html';//Jump to the same-source website
	ifr.onLoad = function() {
		var data = ifr.contentWindow.name;
		alrt(data);
	}
}
</script>
<iframe src='http://other-origin/data.html' style='display:none' onLoad='getData()'></iframe>

other-origin/data.html

var data = {
	name:'xiaoming',
	age: 12
};
window.name = JSON.stringify(data);

(5)WebSocket

WebSocket is a communication protocol that uses ws://(non-encrypted) and wss://(encrypted) as the protocol prefix. This protocol does not implement the same-origin policy, as long as the server supports it, cross-origin communication can be carried out through it.

Request header information: (more origin)
GET/chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

Response header: (if origin is in the whitelist)
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
Reference: https://cloud.tencent.com/developer/article/1148198 Cross-domain solution introduction 2, transferred from github.-Cloud + Community-Tencent Cloud