When cross-domain:
Cross-domain refers to a document or script in one domain trying to request resources in another domain.
In a broad sense, cross-domain:
- Resource jump: A link, form submission.
- Resource embedding: Usually dom tags that refer to external linked files.
- Script requests: JS-initiated Ajax requests, dom and JS object cross-domain operations, etc.
In general, cross-domain is narrowly defined in terms of scenarios where the same origin policy of the browser restricts requests.
Homology, also known as the same origin policy:
The same origin policy is a convention introduced by Netscape to the browser. It is the core and basic security function of the browser. Without the same origin policy, the browser is vulnerable to attacks. Same-origin means that the protocol, domain name, and port are the same. Even if two different domain names point to the same IP address, they are not same-origin.
Several behaviors restricted by the same origin policy:
- Cookie, LocalStorage, and IndexDB cannot be read.
- DOM and JS objects are not available.
- AJAX requests cannot be sent
Cross-domain solutions
1. Cross domains through JSONP
Usually, in order to reduce the load of the Web server, we separate static resources such as JS, CSS and IMG to another server with an independent domain name, and then load static resources from different domain names in the HTML page through corresponding tags, which are allowed by the browser. Based on this principle, we can dynamically create script. Request a reference url to achieve cross-domain communication.
<script>
const random='frankJSONPCallbackName'+Math.random()
window[random]=(data)=>{
console.log(data)
}
const script = document.createElement('script')
script.src = `http://qq.com:8888/friends.js?functionName=${random}`
script.onload=()=>{
script.remove()
}
document.body.appendChild(script)
</script>
Copy the code
2. CORS is cross-domain
For common cross-domain requests, only access-Control-allow-origin is required on the server. This parameter is not required on the front end. If cookie is required, access-Control-allow-origin is required on both the front and back ends.
Note that due to the restriction of the same-origin policy, the cookie read is the cookie of the domain where the cross-domain request interface resides, not the current page
const request = new XMLHttpRequest();
request.open("GET".'http://qq.com:8888/friends.json');
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
console.log(request.response)
}
}
request.send()
Copy the code