Study notes-cross-domain issues in javascript


In js, how to solve cross-domain problems is a very important content. Cross-domain issues cors: cross origin resource share.

Same-origin policy: Only when pages with the same protocol, port, and domain name, the two pages have the same source. As long as the website’s protocol, host, and port number are different, the data request and transmission between websites constitutes a cross-domain call and will be restricted by the same-origin policy.

 

Note: No matter what kind of cross-domain, server-side cooperation is required, and the server-side is the dominant cross-domain.

 

1. Naturally cross-domain label:

In js, there are some tags that can be naturally cross-domain, such as image img or script script.

Having tags in src is inherently cross-domain.

Disadvantages: Only Get requests can be sent, and the response text of the server cannot be accessed (just a one-way request).

2. Use postMessage for cross-domain (cross-page messaging):

// 父  目标.contentWindow.postMessage()
window.addEventListener('message', function(e) { alert(e.data); });
document.querySelector('iframe').contentWindow.postMessage('myMessage', '/'); // '/'表示同域 '*'所有
// 子  找父窗口:window.top || window.parentWindow
window.addEventListener('message', function(e) { alert(e.data);  }); // 在监听事件内找父窗口 e.source
window.parentWindow.postMessage();

3. JSONP cross-domain:

The first step: think about what to do after getting the data across domains, and write a callback function.

Step 2: Make use of the inherent cross-domain feature of the script tag to request the server, get a piece of javascript code, and come back and execute it! This code is the code that calls the callback function.

Step 3: The server cooperates and returns a piece of js code.

<script>
    function callback(data) {
        console.log('拿到的数据:' + data);
        }
</script>
<script src="http://localhost:8888?key=callback"></script>
// 服务器
res.end(`${ funcName }(${ JSON.stringify(data) })`);

4.CORS cross-domain:

$.ajax({
    	url: 'http://localhost:8888',
    	success: function(data) {
    		console.log(data);
    	}
});
// 服务器
res.setHeader('Access-Control-Allow-Origin', '*');  // 允许所有请求跨域
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE')  // 允许请求的类型
res.setHeader('Access-Control-Allow-Headers', 'X-PINGOTHER, Content-Type') // 预检请求
res.setHeader('Access-Control-Max-Age', '1000') // 请求最大响应时间
res.setHeader("Access-Control-Allow-Credentials", 'true') // 是否携带cookie
// ajax设置
"withCredentials": true

5.window.name + iframe:

Utilized features: the cross-domain capability of the iframe tag; the ability of the window.name attribute value to still exist after the document is refreshed (and the maximum allowed is about 2M).

document.querySelector('iframe').contentWindow.name = '张三'; 

6. Modify document.domain across subdomains:

 Prerequisite: These two domain names must belong to the same basic domain name! Moreover, the protocols and ports used must be consistent, otherwise document.domain cannot be used for cross-domain, so it can only cross sub-domains.

There are now two domain names aaa.xxx.com and bbb.xxx.com. Pages embedded with bbb under aaa, because their document.name is inconsistent, cannot operate bbb js under aaa. You can set document.name ='xxx.com'; consistent under aaa and bbb through js to achieve mutual access.

7.WebSocket:

It implements full-duplex communication between the browser and the server while allowing cross-domain communication. It is a great implementation of server push technology.

Disadvantages: WebSocket objects do not support DOM level 2 event listeners, and each event must be defined separately using DOM level 0 syntax.

8. Agency:

The same-origin policy is a restriction on the browser side. The problem can be solved by the server side. DomainA client (browser) => DomainA server => DomainB server => DomainA client (browser).

For example, if the react project uses a proxy, you can configure the "proxy" property in the package.json node.


The above are the methods that some big cows on the Internet often use, but now most of them use three methods: natural cross-domain tags, CORS cross-domain and configuration proxy.

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109479335