AJAX and across domains

This is the 11th day of my participation in Gwen Challenge

Ajax for the front end is a very basic and very practical function, basically we are currently visiting many pages are useful to ajax function. Let’s start talking about AJAX requests and cross domains.

📚AJAX request

Ajax, Asynchronous Javascript And XML.

Before we implement Ajax, let’s take a look at XMLHttpRequest. XMLHttpRequest is the primary API for implementing AJAX on web pages. Many of you probably know AJAX, have used AJAX, but don’t know that it is implemented based on XMLHttpRequest.

So let’s use the XMLHttpRequest API to simulate a GET and POST request.

Simulate GET and POST requests

(1) Simulate GET request:

/** * use XHR emulation to implement the GET request */
const xhr = new XMLHttpRequest();
xhr.open('GET'.'/test.json'.true); // False indicates synchronous request, true indicates asynchronous request
xhr.onreadystatechange = function () {
    // The function is executed asynchronously
    if(xhr.readyState === 4) {if(xhr.status === 200) {// console.log(
            // JSON.parse(xhr.responseText)
            // );alert(xhr.responseText); }}}// Since it is a GET request, just send null
xhr.send(null);
Copy the code

(2) Simulate POST request:

/** * Use XHR emulation to implement post requests */
const xhr = new XMLHttpRequest();
// Simulate a request for a login interface
xhr.open('POST'.'/login'.true); // False indicates synchronous request, true indicates asynchronous request
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4) {if(xhr.status === 200) {console.log(
                JSON.parse(xhr.responseText)
            );
            alert(xhr.responseText);
        }else{
            console.log('Other Circumstances'); }}}const postData = {
    userName: 'zhangsan'.password: 'xxx'
}

xhr.send(JSON.stringify(postData));
Copy the code

2. Encapsulate a simple AJAX

function ajax(url){
    const p = new Promise((resolve, reject) = > {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function(){
            // Status code parsing
            if(xhr.readyState === 4) {if(xhr.status === 200){
                    resolve(
                        JSON.parse(xhr.responseText)
                    );
                }else if(xhr.status === 404){
                    reject(new Error('404 not found'));
                }
            }
        }
        xhr.send(null);
    });
    return p;
}

const url = 'Your JSON data path';
ajax(url)
.then(res= > console.log(res))
.catch(err= > console.error(err));
Copy the code

2. 🧭 status code

After looking at the simulation process above, let’s explain some of the points.

1, XHR. ReadyState

ReadyState status value ReadyState meaning
0 (uninitialized) – The send() method has not been called yet
1 (Loaded) – The send() method has been called and is sitting on sending a request
2 The -send () method is complete and all responses have been received
3 (Interaction) – Parsing the response content
4 The response content is parsed and can be invoked on the client

2, XHR) status

The status status value The status meaning
2xx Indicates that the request was successfully processed. For example, 200
3xx To redirect, go to the browser directly, for example, 301, 302, and 304
4xx The client request is incorrect, such as 404 403
5xx Server side error

3. 🔎 cross-domain

1. Same-origin policy

(1) What is the same-origin policy

The same origin policy is a security policy provided by the browser. The same protocol, domain name, and port of a WEB address can access each other only when the protocol, domain name, and port are the same. If the protocol, domain name, and port are different, the browser forbids the page from loading or executing scripts in different domains.

(2) Why do browsers have same-origin policies?

If there is no same-origin policy, others can easily obtain the cookie information of our website or conduct DOM operations on the webpage.

This is a very scary thing, especially the cookie information, which contains sessionID, which is an important credential of the session session with the server. If someone gets the cookie, it may lead to data theft and other consequences.

(3) What contents are restricted by the same Origin policy?

  • Data stored in a browser, such aslocalStroageCookieIndexedDBCannot be accessed across domains through scripts;
  • Scripts cannot be used to operate in different domainsDOM
  • Can’t passajaxRequest data from different domains.

(4) The same origin policy can be ignored when loading images, JS and CSS

<img src = Cross-domain image address />
<link href = Cross-domain CSS address />
<script src = Cross-domain JS address></script>
Copy the code

As the code above shows, we can ignore the same origin policy when loading images, CSS, and JS of the above types. This is because images, CSS files, and JS files can be cached using CDN, and CDN is usually an outfield. At the same time, JS files can also be implemented across domains through JSONP.

2. Cross-domain solutions

(1) What is cross-domain

  • All cross domains have to go throughserverTerminal permit and coordination;
  • withoutserverEnd allows to achieve cross-domain, indicating that the browser has vulnerabilities, is a danger signal.

(2) Cross-domain solution

1) JSONP (client-side operation)

① The principle of JSONP

JSONP(JSON with Padding) is a “usage mode” of JSON that allows web pages to request data from other domains.

According to the XmlHttpRequest object, the same origin policy is used to exploit the data, and this usage pattern is known as JSONP.

The data captured with JSONP is not JSON, but rather arbitrary JavaScript that is run with a JavaScript interpreter rather than parsed with a JSON parser.

As a result, all JSONP Get requests sent by Chrome are of js type, not XHR.

② JSONP consists of two parts: callback function and data

The callback function is the function that is called to be placed on the current page when the response arrives.

The data is the JSON data passed into the callback function, which is the argument to the callback function.

function handleResponse(response){
 console.log('The responsed data is: '+response.data);
}
var script = document.createElement('script');
script.src = 'http://www.baidu.com/json/?callback=handleResponse';
document.body.insertBefore(script, document.body.firstChild);
/*handleResonse({"data": "zhe"})*/
// The principle is as follows:
// when we request through the script tag
// The background will be based on the corresponding parameters (JSON,handleResponse)
// to generate the corresponding JSON data (handleResponse({"data": "}))
// Finally the returned JSON data (code) will be executed in the current JS file
// Now the cross-domain communication is complete
Copy the code

3. Disadvantages:

  • Only Get requests can be used.
  • Can’t registersuccess,errorThe event listener function, etc., cannot be easily identifiedJSONPWhether the request failed.
  • JSONPExecutes from loading code from other domains,Vulnerable to cross-site request forgery, its security cannot be ensured.

2) CORS (Server operation)

① Principle of CORS

Cross-origin Resource Sharing (CORS) is a specification of the browser technology. It provides a method for Web services to send sandbox scripts from different domains to avoid the same Origin policy of the browser and ensure secure cross-domain data transmission. Modern browsers use CORS in API containers such as XMLHttpRequest to reduce HTTP request risk sources. Unlike JSONP, CORS supports HTTP requirements in addition to GET requirements.

② The cross-domain method of CORS usually operates on the server. The server needs to set the following HTTP headers:

// Set a cross-domain domain name. * is not recommended.
response.setHeader("Access-Control-Allow-Origin"."http://localhost:8080");

// Enter the HTTP request method that is allowed to cross domains
// If method = OPTIONS, it belongs to precheck (complex request). If it is precheck, empty response body can be returned directly, corresponding HTTP status code is 204
response.setHeader("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");

// Set the cross-domain request header to be supported. If this parameter is set to *, the server supports all header fields. X-request-with and Content-type can also be set
response.setHeader("Access-Control-Allow-Headers"."X-Request-With, Content-Type");
After receiving the Request, the server checks the Origin, access-Control-request-method, and access-Control-request-headers fields to confirm that cross-source requests are allowed.

// Indicates the media type information in the specific request
response.setHeader("Content-Type"."application/json; charset=utf-8");

// Set the cache of precheck results in seconds.
response.setHeader("Access-Control-Max-Age".86400);

* access-Control-allow-origin cannot be set to * if cookies are required. * And access-control-allow-credentials need to be set to true *(note that withCredentials = true is required for front-end requests) */
response.setHeader("Access-Control-Allow-Credentials"."false");
Copy the code

4. 📉 Conclusion

The above article gave a brief overview of Ajax and common cross-domain solutions, without going into too much detail. Hope to help everyone!

So much for Ajax and cross-domain information! If you have any questions, you are welcome to comment in the comments section or to communicate with me

  • Pay attention to the public number Monday laboratory, the first time to pay attention to learning dry goods, more interesting columns for you to unlock ~

  • If this article is useful to you, be sure to like it and follow it

  • See you next time! 🥂 🥂 🥂