Cross domain

The same-origin policy

What is a source? Origin is a part of a URL that consists of a protocol, a host name, and a port. As the name implies, only urls that meet the same protocol, domain name, and port number can meet the same origin policy

When does the same origin policy not work? When a source accesses another source’s resources, a cross-source, or cross-domain, occurs.

What does the same origin policy do? The same-origin policy is used to restrict some of these cross-source access, including access to pages in iframe, cookie access to other pages, and AJAX requests. The most common cross-domain scenario is domain name differences

What are the effects of the same Origin policy? The same origin policy not only ensures security, but also brings many problems, for example, the child page in iframe cannot communicate with the parent page, and the browser cannot exchange data with other servers.

Request cross-domain

In order to solve the above problems, cross – domain scheme came into being. There are two main directions, request across domain and page across domain.

Before we look at the request cross-domain scenario, let’s look at the classification of requests, which are simple and non-simple

A simple request

It conforms to the following two characteristics.

  1. The request methods are GET, POST, and HEAD.

  2. The request header can only use the following fields:

    Accept (the type of response that the browser can Accept)

    Accept-language (list of natural languages accepted by the browser)

    Content-type (Request Type, only text/plain, multipart/form-data, Application/X-www-form-urlencoded)

    Content-language (the natural Language that browsers want to adopt)

    Save-data (whether the browser wants to reduce the amount of Data transferred)

GET, POST, and HEAD are the only methods that can be used to share resources across domains. However, non-simple requests have their own processing methods

Non-simple request

A request that does not meet the characteristics of a simple request is a non-simple request

Non-simple requests are preceded by a Preflight of type Option.

Cross-domain resource sharing

Browser section

Will add a Request header field Access – Control – Request – Method, in order to define the Request Method, almost think restful style of HTTP requests in this way…

Access-control-request-method adds Headers that are not part of a simple Request. The value is Authorization (request header field added for cross-domain requests).

This is what the browser client does to the request header. What does the server do when it receives the precheck request?

Server part

After receiving a precheck request, the server adds access-Control-allow-Origin and access-Control-allow-methods to the response header to tell the client the allowed request Methods and return the 204 status code.

Is this the end of it? . no

The server also responds with an Access-Control-allow-headers field based on the browser’s Access-Control-request-HEADERS field to tell the browser what Request header fields the server allows

After the browser gets the header field of the precheck request response, it determines whether the current request server is within the scope of the server’s permission. If so, it continues to send the cross-domain request, and if not, it directly reports an error. THE END…

JSONP

Jsonp is an ajax property that can be configured to cross domains. Jsonp is JSON with Padding and is implemented by filling the JSON number into a callback function. This comparison hack (?? ), which relies on script tags referencing js files across domains without being restricted by the browser’s same-origin policy.

implementation

  1. Declare a function
function fn(result) {
  console.log(result)
}
Copy the code
  1. Write the function name as the variable name to the URL
var url = 'http://www.b.com?callback=fn&params=... ';Copy the code
  1. Create a script tag and assign the URL to the script SRC.
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.src = url;
document.body.appendChild(script);
Copy the code
  1. The server receives the request, parses the URL, processes it, and returns the result to the browser in the form of a callback function
fn({
  list: [],
  ...
})
Copy the code
  1. As soon as the browser receives the js script returned by the request, it executes the file contents, that is, prints the incoming data contents on the console

The disadvantage of the json

  1. Can only send GET requests, limiting parameter size and type;

  2. The request process cannot be terminated, which makes it troublesome to process timeout requests in weak networks.

  3. Unable to catch the exception message returned by the server.

WebSocket

Definition HTML5 specification proposed an application layer of full-duplex protocol, suitable for real-time communication between browser and server scenarios. Establish a Websocket connection on website A, connect to website B, and then call the send method to send a message to the server, listen to onMessage event, and get the response content

var ws = new WebSocket("ws://b.com"); ws.onopen = function(){ // ws.send(...) ; } ws. onMessage = function(e){// console.log(e.data); }Copy the code

Forwarding agent

There are only clients (repeat three times) across domains, so you can try to solve this on the server side, that is, configuring the proxy

The proxy set on the server is the reverse proxy. The proxy set on the client is the forward proxy

The address of the proxy server, such as VPN, must be configured when the forward proxy is used

Reverse proxy Proxy set on the server, for example, nginx

Example of configuring the proxy in webpack-dev-server proxy: {‘/ API ‘: ‘http://localhost:3000’} Example of configuring the code in proxy.js ‘/ API /’: {target: ‘http://10.16.32.172:8096’,}, configure proxy location/API on nginx server {proxy_pass http://localhost:3000; }

All requests prefixed with API are forwarded by the server to the target object and, in the case of the browser, to the current URL

Page cross-domain

In addition to browser requests that cross domains, there are cross-domain requirements between pages, such as communication between parent and child pages when using iframe

1. The document change domain. Domain

If the main domain name is the same and the subdomain name is different, you can change the value of document.domain to cross the domain. www.lagou.com/parent.html and kaiwu.lagou.com/child.html document. Domain = “lagou.com”; With the domain change, parent and child pages can communicate across domains and also share cookies

2. postMessage

Define new HTML5 functions that enable parent and child pages to communicate, regardless of whether the two pages are the same source code a page

// https://lagou.com

var child = window.open('https://kaiwu.lagou.com');

child.postMessage('hi', 'https://kaiwu.lagou.com');

Copy the code

B page

// https://kaiwu.lagou.com

window.addEventListener('message', function(e) {

  console.log(e.data);

},false);

Copy the code

Page B can also send a postMessage method to page A, and page A listens for the Message method.

Use low frequency, remember the principle is OKK