Cross-domain is familiar to most developers, but when it comes to cross-domain, most front-end developers have a solution: just let the server set the parameters. So why does setting these parameters on the server solve the cross-domain problem? Are there any other solutions besides server-side solutions? This article will specifically analyze the causes of cross-domain and other solutions to cross-domain.

First, why cross-domain

1, what is the cross domain If have A page (url:https://www.a.com), A page has an interface request: https://www.b.com/getData; When we send this request to the browser, the browser will return an error message like this:

Access to XMLHttpRequest at ‘https://www.b.com/‘ from origin ‘https://www.a.com‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

When you see this error you know that you have a cross-domain problem. 2, the cause of cross-domain know what is cross-domain, then why will produce cross-domain problems? In order to protect user information security, browsers put forward the same origin policy (note: the same origin policy is restricted only in browsers) :

  • The agreement is the same
  • Domain name is the same
  • The same port

If the above three conditions are met at the same time, we say that two urls are homologous; Therefore, cross-domain problems can arise between non-homologies. Now that we know why cross-domains occur, let’s take a look at several common solutions to cross-domains. Of course, there are other programs, here is not to say, we can query.

Two, several solutions to cross – domain

JSONP, which stands for JSON with padding, is an old way to solve cross-domain problems. In those days, we could solve simple GET requests in this way. But other complex requests, such as POST, require modern solutions, so why can’t JSONP make POST requests? Let’s look at how JSONP solves cross-domain problems:

Although browsers have the same origin policy, script tags are not restricted by the same origin policy, which means that script can be used to make requests to different sources.

Jsonp does not solve cross-domain POST requests because script makes GET requests via SRC.

// Client code
function doJSONPRequestClickHandler() {
    let script = document.createElement('script');
    script.src = 'http://www.b.com/jsonp?callback=handleCallback';
    document.body.appendChild(script);
}
/ / callback
let handleCallback = function(res) {
    console.log(res);
}
Copy the code

The key point of JSONp is the callback argument after http://www.b.com/jsonp?callback=handleCallback, which is processed by the server when it receives the request:

// The server uses nodejs
app.get('/jsonp'.(req, res) = > {
    let cb = req.query.callback;
    res.send(cb + '(" JSONP cross domain succeeded ")');
});
Copy the code

When the browser receives the response from the server that js was successfully loaded, it immediately executes handleCallback(‘ JSONp cross-domain success ‘); So that’s how JSONP works across domains. 2, agency use way to resolve the principle of cross domain also is easy to understand: the same-origin policy only limit in the browser, left the browser environment is not restricted by the same origin policy, so by the agent, will our interface request sent to a homologous agent first, and then through a proxy server forwards to the server. The following is a cross-domain solution via nodeJS middleware proxy:

const http = require('http');
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer();

http.createServer((request, response) = > {
    proxy.web(request, response, {
        target: 'https://www.b.com'.changeOrigin: true}); proxy.on('error'.err= > {
        console.log(err);
    });
}).listen(8081);
Copy the code

3, CORS article mentioned at the beginning of “let the server set parameters” is through CORS to solve the cross-domain, then what is CORS? CORS is cross-source resource sharing. Although the browser has the same origin policy restriction, the browser has opened a “back door” for us. The browser allows to send cross-domain requests, but the server needs to set some specific response headers in the response header:

  • Access-Control-Allow-Origin: | *
  • Access-Control-Allow-Methods: [, ]*
  • Access-Control-Allow-Headers: [, ]*
  • Access-Control-Allow-Credentials: true
  • Access-Control-Allow-Origin

This value tells the client which sources are allowed. It can be set to a specific source or *. When set to allow all sources to make cross-domain requests, be careful;

  • Access-Control-Allow-Methods

It tells the client what methods are allowed for cross-domain requests, such as GET, POST, PUT, etc., which can be set

  • Access-Control-Allow-Headers

This property is required if there are several custom headers in the request header. You can set more than one

  • Access-Control-Allow-Credentials

We need to set it to true if we want to use cookie information in our request. It is important to note that access-Control-allow-origin cannot be set to * if we want to use this attribute. CORS Settings are as follows:

app.post('/saveData'.(req,res) = > {
    res.header('Access-Control-Allow-Origin'.The '*');
    res.header('Access-Control-Allow-Methods'.'POST');
    res.header('Access-Control-Allow-Headers'.'custom');
    console.log(req.body.name);
    res.send('Received data' + req.body.name);
});
Copy the code

3, summarize

The above describes what cross-domain is and why it occurs. Several solutions to generate cross-domain: JSONP, proxy, CORS… ; With the introduction above, we can understand why we need to set the server instead of just saying “let the server set the parameters” when we encounter cross-domain problems. Other cross-domain solutions are not mentioned in this article. You can study them yourself if you are interested, such as through websocket and IFrame.