What is cross-domain?

1. The same origin policy is as follows:

URL instructions Whether to allow communication
http://www.a.com/a.js http://www.a.com/b.js Under the Same domain allow
http://www.a.com/lab/a.js http://www.a.com/script/b.js Different folders under the same domain name allow
http://www.a.com:8000/a.js http://www.a.com/b.js Same domain name, different port Don’t allow
http://www.a.com/a.js https://www.a.com/b.js Same domain name, different protocol Don’t allow
http://www.a.com/a.js http://70.32.92.74/b.js The domain name and corresponding IP address of the domain name Don’t allow
http://www.a.com/a.js http://script.a.com/b.js The primary domain is the same, but the subdomain is different Don’t allow
http://www.a.com/a.js http://a.com/b.js Same domain name, different secondary domain name (same as above) Disallow (access is also disallowed in the case of cookies)
http://www.cnblogs.com/a.js http://www.a.com/b.js Different domain name Don’t allow

Two points in particular:

First: if protocols and ports cause cross-domain problems, the “foreground” is powerless;

Second: in terms of cross-domain problems, domains are only identified by “the head of the URL” without trying to determine whether the same IP address corresponds to two domains or whether two domains are on the same IP address.

The same origin policy restricts the following behaviors:

1.) Cookie, LocalStorage, and IndexedDB cannot be read. 2.) DOM and Js objects cannot be obtainedCopy the code

2. Cross-domain solutions

Hash + iframe 4. Window. name + iframe 5. PostMessage 6. Cross-domain resource sharing (CORS) 7, Cross-domain nginx proxy 8, cross-domain NodeJS middleware proxy 9, cross-domain WebSocket protocol

First, cross domains through JSONP

Usually, in order to reduce the load of the Web server, we separate static resources such as JS, CSS and IMG to another server with an independent domain name, and then load static resources from different domain names in the HTML page through corresponding tags, which are allowed by the browser. Based on this principle, we can dynamically create script. Request a reference url to achieve cross-domain communication.

1.) Native implementation:

 <script>
    var script = document.createElement('script');
    script.type = 'text/javascript';

    // Pass the name of a callback function to the back end, so that the back end can execute the callback function defined in the front end when it returns
    script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
    document.head.appendChild(script);

    // The callback executes the function
    function handleCallback(res) {
        alert(JSON.stringify(res));
    }
 </script>
Copy the code

The server returns the following (executes the global function when it returns) :

handleCallback({"status": true."user": "admin"})
Copy the code

2.) the vue. Js:

this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) = > {
    console.log(res); 
})
Copy the code

Examples of back-end Node.js code:

var querystring = require('querystring');
var http = require('http');
var server = http.createServer();

server.on('request'.function(req, res) {
    var params = qs.parse(req.url.split('? ') [1]);
    var fn = params.callback;

    // jsonp returns Settings
    res.writeHead(200, { 'Content-Type': 'text/javascript' });
    res.write(fn + '(' + JSON.stringify(params) + ') ');

    res.end();
});

server.listen('8080');
console.log('Server is running at port 8080... ');
Copy the code

Disadvantages of JSONP: Only one get request can be implemented.

Ii. Cross-domain Resource Sharing (CORS)

Normal cross-domain request:

Access-control-allow-origin can be set only on the server. The front end does not need to be set. If cookie request is required, the front and back ends need to be set.

Note that:

Because of the same-origin policy restriction, the cookie read is the cookie of the domain where the cross-domain request interface resides, not the current page. Nginx reverse proxy sets proxy_cookie_domain and cookieDomainRewrite (NodeJs).

Currently, all browsers support this functionality (IE8+ : IE8/9 requires the use of XDomainRequest objects to support CORS), and CORS has become a mainstream cross-domain solution.

1. Front-end Settings:

1.) Native Ajax

// Set whether cookies are included in the front end
xhr.withCredentials = true;
Copy the code

Sample code:

var xhr = new XMLHttpRequest(); // Ie8/9 must be window.xdomainRequest compatible

// Set whether cookies are included in the front end
xhr.withCredentials = true;

xhr.open('post'.'http://www.domain2.com:8080/login'.true);
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.send('user=admin');

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); }};Copy the code

2.) VUE framework

A.) Axios Settings:

axios.defaults.withCredentials = true
Copy the code

B.) Vue-resource Settings:

Vue.http.options.credentials = true
Copy the code

2. Server Settings:

If the Settings are successful, the console of the front-end browser will not display cross-domain error messages; otherwise, the Settings are not successful.

1.) Nodejs

var http = require('http');
var server = http.createServer();
var qs = require('querystring');

server.on('request'.function(req, res) {
    var postData = ' ';

    // Data block received
    req.addListener('data'.function(chunk) {
        postData += chunk;
    });

    // Data is received
    req.addListener('end'.function() {
        postData = qs.parse(postData);

        // Cross-domain background Settings
        res.writeHead(200, {
            'Access-Control-Allow-Credentials': 'true'.// The backend allows sending cookies
            'Access-Control-Allow-Origin': 'http://www.domain1.com'.// Allowed domain (protocol + domain name + port)
            /* * Set the cookie to domain2 instead of domain1, because the backend cannot write cookies across domains (nginx reverse proxy can do this), * but as long as domain2 write cookie authentication once, All subsequent cross-domain interfaces can obtain cookies from domain2, so that all interfaces can cross-domain access */
            'Set-Cookie': 'l=a123456; Path=/; Domain=www.domain2.com; HttpOnly'  // HttpOnly prevents js from reading cookies
        });

        res.write(JSON.stringify(postData));
        res.end();
    });
});

server.listen('8080');
console.log('Server is running at port 8080... ');
Copy the code

Ajax profile

Definition 1.

Ajax, also known as Asynchronous Javascript And XML, is a technique for updating parts of a web page without having to reload the entire page.

Ajax allows web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that part of a web page can be updated without reloading the entire page.

2. The four basic steps of Using Ajax are easy to understand

The first step is to create an XMLHttprequest object, which is used to exchange data with the server.

var xmlhttp =newThe XMLHttpRequest ();Copy the code

Second, use the open () and send () methods of the XMLHttprequest object to send the resource request to the server.

xmlhttp.open(method,url,async) 
/ / such as
xmlhttp.open(get, 'http://193.168.22.11:8000'.true)
Copy the code

Method includes get and POST, URL is mainly the path to a file or resource, async parameter is true(asynchronous) or false (synchronous)

Third, get the response from the server using the responseText or responseXML property of the XMLHttprequest object.

Step 4, onReadyStateChange, when we send a request to the server, and we want the server to respond and do something we need to use onReadyStateChange, The onReadyStateChange function is triggered each time the readyState of the XMLHttprequest object changes.

The readyState property, the state of the XMLHttpRequest object, changes from 0 to 4, 0 indicating that the request was not initialized, 1 indicating that the server connected successfully, 2 indicating that the request was received by the server, 3 indicating that the request was processed, and 4 indicating that the request was completed and the response was ready.

/** 1. Create a connection
var xhr = null;
xhr = new XMLHttpRequest()
/** 2. Connect to server **/
xhr.open('get', url, true)
/** 3. Send request **/
xhr.send(null);
/** 4
xhr.onreadystatechange = function(){
	if(xhr.readyState == 4) {if(xhr.status == 200){
			success(xhr.responseText);
		} else { 
			/** false **/fail && fail(xhr.status); }}}Copy the code

Max – age and Expires

The main point is to understand a relative Expires and an absolute max-age.

A, the Max – age

Max-age is HTTP/1.1, which refers to the lifetime of a file in our web after the user accesses (requests). It is a relative value, as opposed to Request_time. For example, if the a.HTML user request time is 18:00 and max-age is set to 600, it will expire in 18:00+600 seconds, i.e. 600 seconds after 18:00. The default max-age is computed from Expires.

Second, the Expires

Expires is HTTP/1.0 and is a bit more troublesome than Max-age. Expires can be specified in one of two ways, depending on whether the Apache setting is A or M.

1. Last access time (Atime) when Apache uses time A to do Expires. This sets it to the same value as max-age, because max-age is the Atime of the relative file.

Example: ExpiresByType text/ HTML A600

From the above we know that Apache set Atime to expire at 600 seconds. Expires=18:00+600=18:10 max-age=18:00+600=18:10

2. Absolute change time (MTime)

This is divided into two cases, let’s take A. tm for example: assume that the file creation time is 18:00.

  • When a Request is set to 18:00, Expires is set to 600 seconds. Expires=18:00+600=18:10 max-age=18:00+600=18:10 Indicates that Expires equals max-age

  • When the Request is 18:20, the expiration time is 600 seconds

    Expires=18:00+600=18:10(because when set to Mtime, the time is determined by the time the file was created) max-age=18:20+600=18:30 Indicates that Expires does not equal max-age

When using MTime, the initial Expires value is when the file was created. The initial value of max-age is the time when the client requests data.

Also note that max-age is optimized for clearcases like the one above, so the expiration time is 18:30.