There is no pure front-end cross-domain solution, encounter cross-domain, please find the back-end negotiation solution!

What is cross-domain?

The same origin policy restricts how documents or scripts loaded from one source interact with resources from another. This is a key security mechanism for isolating potentially malicious files. – the MDN

Cross-domain is generated by the same origin policy of the browser. Cross-domain problems occur when you access (request) resources that differ from the protocol, domain name, or port of the current page.

There are three common solutions.

1. jsonp

Jsonp has nothing to do with XMLHttpRequest at all.

Some tags in HTML have the ability to access resources across domains. For example, we request data from other servers using script tags, a technique we call JSONP.

To do this, create a script tag, assign the requested URL to SRC, add it to document, and then the browser will send an HTTP request for GET to download the URL to which the SRC attribute points.

Schematic diagram:

I won’t post the code, but if the request times out, it will raise the onError event of script tag, similar

a = new Image();
a.src = "http://www.baidu.com"; 
a.onerror = function(){
    console.log('load failed')}Copy the code

Its onError event is raised when the image resource request fails.

2. Cors cross-domain resource sharing

This is handled by the back end; the front end doesn’t need to know much about it. This is done primarily by setting the access-Control-Allow-Origin field of the responseHeader

Here you can refer to “Cross-domain resource Sharing CORS: Ruan Yifeng”. What is a simple request and what is not a simple request? When will the browser try to make an options request first?

Schematic diagram:

CORS

3. The agent

By proxy I mean mid-tier proxy and NGINx reverse proxy.

In my understanding, these two things are similar, because the server handles them, and the server does not have cross-domain problems.

For example, I use a Node service as an intermediate forwarding layer. My request to the homologous in www.ccc.com/a.html www.ccc.com/api/v1/getUserAge?id=106 launched, node service receives the request, In the node server to another server such as www.aaa.com/api/v1/getUserAge?id=106 request, it returns the results, such as the request again results back to www.ccc.com/a.html.

Schematic diagram:

The node forwards

I haven’t used nginx much, but it’s probably about the same, there’s a blocker for external and internal requests and stuff like that, set up forwarding in there.

Write here, if there is a wrong understanding, also please correct, thank 🙏 🙂