“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Front row friendship tips, this article is an introductory article, no in-depth knowledge points.

Cross-domain is a question that will be asked in the front-end interview, this article stands in a beginner’s perspective to look at cross-domain related knowledge.

What is cross-domain

Cross-domain problems arise from restrictions on browser same-origin policies, including DOM same-origin restrictions and Ajax same-origin restrictions, and this article explores Ajax cross-domain. Ajax cross-domain refers to the fact that ajax on a page can only request data of the same origin as the current page, and that the browser blocks the returned data if the requested data does not meet the requirements. Same-origin means that the protocol, domain name, and port number must be the same (different domain names with the same IP address are also cross-domain). The same origin policy is used to prevent CSRF attacks. It can effectively avoid risks caused by malicious attacks. The same origin policy for browsers makes network access more secure.

However, in actual development and production, resources from other sites are often obtained and used, and cross-domain requests need to be made, which requires special processing methods to enable us to obtain the data we want.

Therefore, cross-domain is limited to browsers, because browsers intercept different sources of data. Cross-domain is sometimes unavoidable, and we need to take measures to implement cross-domain requests.

The way a cross-domain request is made

There are many ways to implement cross-domain requests, and here are a few common ones I know of:

JSONP

First of all, the most famous way is JSONP. Before learning JSONP, we should know that although browsers have homologous restrictions, but there are three tags that do not conform to this restriction: SRC (fetch image), href (fetch CSS),

Now that you know how JSONP works, it’s easy to look at JSONP. Let’s look at a simple example.

Assuming that the client needs to retrieve JSON data {code: 200, data: “success”}, a simple server implementation is as follows (using the node.js native HTTP module)

const http = require('http');
const url = require('url');

http.createServer((req, res) = > {
  if (req.url.startsWith('/test')) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    const callback = url.parse(req.url, true).query.callback;
    const result = '{code: 200, data: "success"}';
    const jsonpCallback = `${callback}(${result}) `
    res.end(jsonpCallback);
  }
}).listen(8888);
Copy the code

The client requests are as follows

<script>
function jsonpCallback (res) {
    // The result of the request is processed here
    console.log(res);
}
</script>
<script src="Http://127.0.0.1:8888/test? callback=jsonpCallback"></script>
Copy the code

On the client side, a jSONP method name is passed through the request parameter. On the server side, the returned result is wrapped with the specified JSONP method call, which is equivalent to requesting a section of JS. The real return result can be obtained through the function call parameter. This allows you to circumvent browser same-origin restrictions and get cross-domain request results.

Jsonp is a common cross-domain approach, and there are many front-end JSONP request wrappers that are implemented by dynamically creating script tags that we can call directly. Jsonp is compatible with all browsers, but only supports GET requests.

CORS

CORS Chinese is “cross-domain resource sharing” (cross-origin resource sharing), is a new cross-domain way supported by W3C, it is different from other ways, it is written standard cross-domain request way, modern browsers generally support. It allows cross-domain requests to be sent as normal Ajax requests, provided the server supports them. CROS supports other kinds of requests besides GET requests.

CORS requests are classified into simple requests and non-simple requests. Simple requests must meet the following two conditions:

  1. The request method is one of three:

    • HEAD
    • GET
    • POST
  2. HTTP headers do not exceed the following fields:

    • Accept
    • Accept-Language
    • Content-Language
    • Last-Event-ID
    • Content-type: Application/X-www-form-urlencoded, multipart/form-data, text/plain

All other requests are complex, and browsers handle simple and complex requests differently.

For simple requests, the browser adds the Origin field in the request header to identify the source of the request. The server checks the received request. For those that meet the requirements, the server adds related fields starting with Access-Control-allow – in the return header.

For a simple request, before the formal request will increase an OPTIONS request for “preview”, the request will bring the source, the server will check whether accords with a condition, if do not conform to the returns a header information without any CORS related fields, the browser will know the request does not allow, triggering error, stop continue to send the request.

CROS focuses on the server. As long as CROS is configured, requests can be sent normally, which is very convenient and secure. The specific server configuration depends on the different implementation of the server.

Server agent

This is the ultimate solution, because the restriction only exists in the browser, it doesn’t exist in other environments, and it doesn’t exist in the server, so just broker the request on the server, and the request becomes homogenous.

The server proxy can use Nginx as the proxy, or nodeJS middleware, etc. Either way, its purpose is to bypass the limitations of the browser, from the perspective of the browser, or the same source access, naturally there is no cross-domain problem.

These are the main ways ajax can cross domains, and there are specific solutions to another kind of cross-domain interaction restriction between pages. The common ways are document.domain, window.name, and postMessage.

Added: Other cross-domain solutions

The iframe cross-domain

Another problem with browser homology restriction is that frameworks in different domains in the browser cannot interact with JS. Here are a few ways to overcome this limitation.

Document.domain to cross subdomains

This method is applicable to the case where the main domain name is the same but the subdomain name is different. For example, if a page is http://a.test.html and b page is http://b.test.com, you can set document.domain=test.com for the two pages. The iframe can then be manipulated across domains using parent or window[‘iframename’].

Window. The name across domains

The window object has a name attribute, which has a characteristic: during the lifetime of a window, all pages loaded by the window share the same window.name, even if the page and even the domain name are different. Each page has read and write permissions to window.name, and the name length can be up to 2MB, providing an opportunity to share resources across domains.

The location. The hash across domains

Location. hash cross-domain takes advantage of the child frame’s ability to modify the parent frame’s SRC hash without refreshing the page. The number of bytes of data that can be passed in this way is finite.

HTML5’s postMessage crosses domains

Window.postmessage (Message,targetOrigin) is an HTML5 API that allows two Windows to send messages across domains. It can implement data transfer between the page and the new window it opens, and message transfer between multiple Windows. Cross-domain issues in scenarios such as pages and nested IFrame messaging.

The Websocket protocol is cross-domain

Websocket is a new protocol that is different from HTTP. It implements full-duplex communication between browser and server, and allows cross-domain communication. The detailed introduction of Websocket is not expanded here.