1. Same-origin policy
- What is homology
If the protocol, domain name, and port number of two urls are the same, the two urls are of the same origin
Window. origin or location.origin can get the current source
- What is the same origin policy
Prevents javascript scripts in one domain from interacting with content in another domain.
What is cross-domain
When the protocol, domain name, or port of a request URL is different from the current page URL, it is called cross-domain
Current page URL | Url of the requested page | Whether the cross-domain | why |
---|---|---|---|
www.test.com/ | www.test.com/index.html | no | Same-origin (same protocol, domain name, and port number) |
www.test.com/ | www.test.com/index.html | Cross domain | Different protocols (HTTP/HTTPS) |
www.test.com/ | www.baidu.com/ | Cross domain | Different master domain name (test/baidu) |
www.test.com/ | blog.test.com/ | Cross domain | Different subdomains (WWW /blog) |
www.test.com:8080/ | www.test.com:9999/ | Cross domain | Different port numbers (8080/9999) |
Three, two solutions to cross domain
- JSONP
The first thing to know is that the SRC of the script tag, the SR C of the IMG tag, or the href of the link tag, which are not restricted by the same origin policy, will send a GET request to the static resource
<body>
<img src="https://img-pre.ivsky.com/img/tupian/pre/201402/18/pikachu.jpg" />
</body>
Copy the code
This allows JSONP to cross domains using the SRC attribute of the Script tag
The idea: A web page requests JSON data from the server by adding a script element. The server receives the request and returns the data as an argument to a named callback function.
JSON cross-domain implementation
const script = document.createElement('script')
script.src = `http://xx.com:8888/friends.js?callback=func`
document.body.appendChild(script)
function func(data){
console.log(data)
}
Copy the code
- CORS
CORS stands for Cross-Origin Resource Sharing. It is a W3C standard and a fundamental solution for cross-source AJAX requests.
For common cross-domain requests, you only need to set access-Control-allow-Origin on the server