This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging
0. Come first
😭! In the first year of my freshman year, I tried to do some small projects with jquery at the beginning of my study, which bothered me for a winter vacation !!!! At that time, there was no cross-domain this concept, so it began crazy Baidu… In order not to delay the progress, a front and back end of the separation of the project was forced into no separation, later fortunately, in the eve of the smooth solution, the separation of the “no” word, and also completed the project on time!!
(delayed for a month or so should also be called on time to complete it, no matter, first reward yourself a 🍗~)
Cross-domain problem has really become a shadow in my heart for a period of time, and then when it comes to cross-domain, my heart is afraid of thieves!
Recently reviewing the network part, I brush the cross-domain knowledge, so I combined my lifelong learning (plus a lost data collected), summed up some cross-domain knowledge.
1. What is cross-domain?
For example, 🌰. The website of my blog is blog.wangez.site:8080
The first HTTPS is called the protocol, the next blog.wangez.site is called the domain name, and the last 8080 is called the port number
(note: the real blog url does not take 8080, my blog, said is for example 🌰, will not be taken seriously!!) .
If the address requested by an interface on the current page differs from the address of the current page by protocol, domain name, or port, the interface is said to be cross-domain
2. Why cross-domain?
The browser uses the same origin protocol policy to ensure web page security
This part of the following excerpt from MDN, want to learn more about this part can go (MDN) (the browser’s same-origin policy – Web security | MDN (mozilla.org)).
The same origin policy is an important security policy that restricts how an Origin document or script it loads can interact with the resources of another source. It can help block malicious documents and reduce the media that may be attacked.
Two urls are homologous if their protocol, port (en-us) (if specified), and host are the same. This scheme is also known as a “protocol/host/port tuple”, or simply a “tuple”. (” tuple “refers to a group of items as a whole, the general form of double/triple/quadruple/quintuple/etc.)
The following table gives the comparing with the URL http://store.company.com/dir/page.html source example:
URL | The results of | why |
---|---|---|
http://store.company.com/dir2/other.html |
homologous | Only the path is different |
http://store.company.com/dir/inner/another.html |
homologous | Only the path is different |
https://store.company.com/secure.html |
failure | Agreement is different |
http://store.company.com:81/dir/etc.html |
failure | Different ports (http:// The default port is 80. |
http://news.company.com/dir/other.html |
failure | The host different |
3. An error message is displayed across domains
When we test the interface, we see that the data does not come as promised, open our universal browser console, see this error, do not hesitate, is to meet the cross-domain problem!
4. Cross-domain solutions
4.1 cors
This is one of the most common solutions I use to write projects. It is also the most popular solution at the moment. It is simple and fast to solve cross-domain problems by setting up the backend
The legendary backend cross-domain!
res.setHeader('Access-Control-Allow-Origin'.The '*'); // What is the allowed cross-domain source address, which can be set to * or your source address
res.setHeader("Access-Control-Allow-Headers"."Origin, X-Requested-With, Content-Type, Accept"); // Set the return data type
res.setHeader("Access-Control-Allow-Methods"."GET, PUT, OPTIONS, POST"); // Control which requests are allowed across domains
res.setHeader("Access-Control-Allow-Credentials".true); // Whether to carry cookies across domains
Copy the code
4.2 the json
The idea is that the script tag can request resources across domains, concatenating callback functions as parameters in the URL
The legendary front end cross domain! But need to back end friends to cooperate with us 🙄
The backend receives the request, calls the callback function, and returns the data as a parameter. Note that the response header returns the document type, which should be set to javascript
Res.setheader (‘content-type’, ‘application/javascript’) // Don’t forget to set this!
<script>
function JsonpCallback(data) {
// This is where the data returned by the backend is processed
console.log(data);
}
</script>
<script src="http://127.0.0.1:12345/jsonp/callback=JsonpCallback"></script>
Copy the code
4.3 postmessage
This is an approach THAT I haven’t heard of, and it takes advantage of the HTML5 API for specific usage scenarios.
Usage scenario: A page embedded with another iframe page,
Use postMessage to send data on the home page and listeners to receive data on the Iframe page
` ` ` / / main page iFrame. Onload = function () {iFrame. ContentWindow. PostMessage ({MSG: 'MessageFromIndexPage'}, '\ *'); } // iframe page window.addeventListener ("message", function (event) {console.log(' here is the message received from the parent page, The message content is in the event.data property ', event)}, false) 'Copy the code
4.4 Other methods: Node middleware, Nginx reverse proxy, Websocket, etc
This is mainly because the same origin policy is a limitation of the browser, and there is no limitation between servers
This time we take a pineapple 🍍, little red to green new toys (interface requests), but didn’t give him (the same-origin policy), little green went to the xiao LAN, so little red said to xiao LAN, I want a little green new toy (ready to make forward middleware or agent), xiao LAN with small green go to the new toy (got to data, Indicate success) and hand over the new toy to Xiao Hong (cross-domain solved).
In this case, I only have contact with Node middleware and nginx reverse proxy, and do not have a very deep understanding, so I will not make a fool of myself, and I will fill this hole in the future.
5. The last
Cross-domain is a very common problem, which also appears frequently in the interview questions. I hope everyone can solve this problem smoothly when they encounter this problem. Although we now write the project, most of the framework for us to configure agents (Vue proxyTable agent, etc.), but I think it is very helpful for us to understand the root cause of self-improvement!