Cross-domain problems arise
Cross-domain refers to requesting resources from one source’s web page to another source’s web page. However, this is generally not possible because it is caused by the same origin policy of the browser, a security restriction that the browser imposes on JavaScript.
The same-origin policy
The Same Origin Policy (SOP) is a security policy enforced by Web browsers to control access to data between Web sites and Web applications. Without SOP, any web page will be able to access the DOM of other pages. This would allow it to access potentially sensitive data from another web page and perform operations on other web pages without the user’s consent.
To put it simply, if JS is running in source A, then it can only fetch data from source A, not source B, that is, cross-domain is not allowed.
What is the source?
Source = Protocol + domain name + port numberCopy the code
If the protocol, domain name, and port number of two urls are the same, the two urls are homologous. For example, baidu.com and www.baidu.com are from different sources
There are two common solutions
In reality, however, content is shared across domains. Here are the two most common ways
CORS
CORS is a W3C standard, which stands for “Cross-origin Resource Sharing”.
CORS requires both browser and server support. Currently, all browsers support this function, and Internet Explorer cannot be lower than Internet Explorer 10.
The key to CORS communication is the server, which needs to realize the CORS interface. The most critical step is to configure the access-Contro-AIIOW-Origin attribute in the response header
Access-contro-aiiow-origin: specifies the URL that allows cross-domain AccessCopy the code
👉 Refer to the following article for a detailed interpretation of CORS:
Cross-source Resource Sharing (CORS)
Cross-domain resource sharing (CORS
JSONP
JSONP is a common method of cross-source communication between servers and clients and is simple to use.
💁🏼♀️ : Before we get to JSONP, let’s discuss the use of script tags in HTML files to reference JS files from other websites.
Sometimes for convenience, we will directly reference JS libraries on https://www.bootcdn.cn/ and other websites in HTML through script tags. We can successfully reference JS and successfully execute relevant operations. Is this considered cross-domain? The answer is that this is not cross-domain, this practice is not restricted by the same origin policy, because it is just used, and does not get the specific contents of the JS file.
The basic idea of JSONP is that a web page requests JSON data from the server by adding a
Here is a brief demonstration of the client operation:
The client
function jsonp(url) {
return new Promise((resolve, reject) = > {
const random = "JSONPCallbackName" + Math.random();
window[random] = data= > {
resolve(data);// Cross-site callback, wait until the import JS file gets the data
};
const script = document.createElement("script");
script.src = `${url}? callback=${random}`;
script.onload = () = > {
script.remove();
};
script.onerror = () = > {
reject();
};
document.body.appendChild(script);
});
}
jsonp("http://example.com:8888/example.js").then(data= > {
console.log(data);
});
Copy the code
The above code encapsulates JSONP with promise by dynamically adding
💁🏼♀️ Note that the name of the callback can be random. The requested query string has a callback parameter that specifies the name of the callback function to inform the server, which is required for JSONP. Finally, after the data can be deleted script tags, so as not to cause HTML page chaos.
The example.js file introduced
window[random](JSONData)Copy the code
JS files requested by the
advantages
- Compatible with Internet Explorer of older versions
- Data can be accessed across domains
disadvantages
- Because it is a script tag to request the referenced JS, it cannot judge the status of the whole process like the Ajax request in method 1. Besides, it cannot get status and header, but can only know failure or success. Only onload and onError callback functions are available.
- Because it is a script tag, only get requests can be sent. Post is not supported
A comparison of the two methods
-
JSONP supports only GET requests, and CORS supports all types of HTTP requests.
-
JSONP has the advantage of supporting older browsers (IE 6,7,8,9) and being able to request data from sites that do not support CORS.
reference
Browser same origin policy and its circumvention method