Notes source: Silicon Valley: 3 hours from Ajax to Master

[TOC]

I can’t stop AJAX in three sentences

Hello, everyone. I am a high-quality male ape coder proficient in AJAX. Three sentences make AJAX irresistible to me

  • What is theAJAX?
  • Why do you want toAJAX?
  • How doAJAX?

Let’s take a closer look at AJAX with these three sentences

🤓 👔 🤳 👖 👞 👞Copy the code

1. Introduction to AJAX


AJAX is Asynchronous JavaScript And XML

AJAX allows you to send asynchronous requests to the server from within the browser, with the biggest advantage: no refresh to retrieve data

AJAX is not a new programming language, but a new way to use existing standards together

Scenario 1: Keyword retrieval

Scenario 2: Registration user name duplication detection

Scenario 3: Menu details

Scenario 4: Level-2 level-3 menu classification

Scenario 5: Load more

Benefits: Lazy loading, on-demand loading, improve resource utilization, accelerate the overall page loading speed, improve user experience

2. Introduction to XML


XML extensible Markup Language, designed to transfer and store data

XML is similar to HTML, except that HTML has predefined tags. XML has no predefined tags, but all custom tags, which represent some data

For example, I have a student data: name=” Sun Wukong “; age=18; Gender = “male”;

Expressed in XML:

<student>
    <name>The Monkey King</name>
    <age>18</age>
    <gender>male</gender>
</student>
Copy the code

It has now been replaced by JSON. Expressed in JSON:

{"name":"Sun Wukong"."age":18."gender":"Male"}
Copy the code

3. AJAX features


The advantages of AJAX

  • You can communicate with the server side without refreshing the page
  • Allows you to update parts of the page based on user events

The disadvantage of AJAX

  • Cannot rollback without browsing history
  • Cross-domain problems exist (homologous)
  • SEO (Search Engine Optimization) is not friendly and crawlers cannot crawl

4. HTTP protocol


Hypertext Transport Protocol (HTTP) specifies the rules for communication between the browser and the World Wide Web server

The focus is on format and parameters

The request message

  • The request line
    • Request type:GET/POST/PUT/DELETE/PATCH
    • URL path:s? ie=utf-8
    • HTTP version:HTTP / 1.1
  • Request header
    • Host: atguigu.com
    • Cookie: name=guigu
    • Content-type: application/x-www-form-urlencoded
    • User-Agent: chrome 83
    • .
  • Blank line: Fixed format, must have
  • Request body:GETRequest, request body is empty;POSTRequest, the request body may not be empty
    • username=admin&password=admin

The response message

  • Response line

    • HTTP version:HTTP / 1.1
    • Response status code:200/404/500
    • Response status string:OK/Not Found/Internal Server ErrorCorresponds to the response status code
  • Response headers

    • Content-Type: text/html; charset=utf-8
    • Content-length: 2048
    • Content-encoding: gzip
    • .
  • Blank line: Fixed format, must have

  • Response body

    <html>
        <head>
        </head>
        <body>
            <h1>Response body</h1>
        </body>
    </html>
    Copy the code

Status code classification table

category describe
1xx Informational(Informational status code) The request is being processed
2xx Success(Success Status code) The request is successfully processed
3xx Redirection Additional action is required to complete the request
4xx Client error The client request fails
5xx Server Error The server failed to process the request

Common response status codes

Status code Status string describe
200 OK The request is successful
302 Found The URL of the requested resource is temporarily changed to the URL provided by Location
304 Not Modified Resources not changed
308 Permanent Redirect Permanent redirection
400 Bad Request The request syntax is wrong and the server cannot recognize it
401 UnAuthorized The client did not authorize the request
403 Forbidden Server reject response
404 Not Found The URL is invalid or the URL is valid but has no resources
500 Internal Server Error Server internal error
502 Bad Gateway An invalid response was received from the upstream server when the server was used as a gateway. Procedure
503 Service Unavailable Unable to service. It usually occurs when maintenance is down or service is overloaded
504 Gateway Timeout Gateway timeout
505 Http Version Not Supported The sent request is not supported by the HTTP version server

5. Development preparation


Installation Node. Js

  • Official website: nodejs.org/en/
  • CMD type commandnode -vIf the version number is displayed, the installation is successful
node -v
Copy the code

Using the express

  • Official website: www.expressjs.com.cn/
  • NPM (Node Package Manager):Node.jsPackage manager fornodePlug-in management (including installation, uninstallation, managing dependencies, and so on)

Open the terminal and type the command

#Initialize the
npm init --yes
#Installing the Express Framework
npm i express
Copy the code

Create JS files and write code

// 1
// const express = require('express');
import express from 'express';

// create an application object
const app = express();

// 3. Create routing rules
// request Encapsulates request packets
// Response Indicates the encapsulation of the response packet
app.get('/'.(request, response) = > {
    // Set the response
    response.send('Hello Express');
});

// 4. The listener port starts the service
app.listen(8000.() = > {
    console.log("Service started, listening on port 8000...");
});
Copy the code

Open the terminal again and type the command node js file name

Node01-express basically uses.jsCopy the code

Service started, listening on port 8000… “, the startup is successful

We open the browser, visit http://127.0.0.1:8000/, Hello Express appears, verify OK

Case preparation

The new HTML

.<style>
    #result {
        width: 200px;
        height: 100px;
        border: 1px solid #90b;
    }
</style>.<button>Click Send request</button>
<div id="result"></div>
Copy the code

Modify the routing rules slightly

app.get('/server'.(request, response) = > {
    // Set the response header to allow cross-domain
    response.setHeader('Access-Control-Allow-Origin'.The '*');
    // Set the response body
    response.send('Hello Express');
});
Copy the code

According to the above steps to start after the express, the browser to http://127.0.0.1:8000/server, can normal visit, and we set the header information in response headers

AJAX sends GET requests


  • 1. Create an object

    const xhr = new XMLHttpRequest();
    Copy the code
  • 2. Initialize

    xhr.open('GET'.'http://127.0.0.1:8000/server');
    Copy the code
  • 3, send,

    xhr.send();
    Copy the code
  • 4, event binding, processing the results returned by the server

    xhr.onreadystatechange = function () {... }Copy the code
  • readeyState

    • 0: not initialized
    • 1: The open method is called
    • 2: The send method is called
    • 3: The server returns partial results
    • 4: The server returns all results
  • Status: indicates the status code

  • StatusText: indicates the status string

  • GetAllResponseHeaders () : response header

  • Response: Response body

The complete code

const result = document.getElementById('result');
// Button binding events
const button = document.getElementsByTagName('button') [0];
button.onclick = function () {
    // create an object
    const xhr = new XMLHttpRequest();
    // 2
    xhr.open('GET'.'http://127.0.0.1:8000/server');
    // 3
    xhr.send();
    // 4, event binding, processing the result returned by the server side
    xhr.onreadystatechange = function () {
        // The server returns all results
        if (this.readyState === 4) {
            / / 2 xx success
            if (this.status >= 200 && this.status < 300) {
                // Status code and status string
                console.log(this.status); / / 200
                console.log(this.statusText); // OK
                / / response headers
                console.log(this.getAllResponseHeaders()); // content-length: 13 content-type: text/html; charset=utf-8
                / / response body
                console.log(this.response); // Hello Express
                // Set the response body content to text
                result.innerHTML = this.response; }}}; }Copy the code

The effect

GET sets the request line

xhr.open('GET'.'http://127.0.0.1:8000/server? a=100&b=200&c=300');
Copy the code

AJAX sends POST requests


Let’s modify the previous send request code slightly by changing the GET request to POST

const result = document.getElementById('result');
result.addEventListener('mouseover'.function () {
    const xhr = new XMLHttpRequest();
    xhr.open('POST'.'http://127.0.0.1:8000/server');
    xhr.send();
    xhr.onreadystatechange = function () {
        if (this.readyState === 4 && this.status >= 200 && this.status < 300) {
            result.innerHTML = this.response; }}; });Copy the code

Test result in browser, error reported

This is because server.js only sets routing rules for GET requests and does not create routing rules for POST requests

Let’s add, again only slightly modified, get to POST

app.post('/server'.(request, response) = > {
    // Set the response header to allow cross-domain
    response.setHeader('Access-Control-Allow-Origin'.The '*');
    // Set the response body
    response.send('Hello Express');
});
Copy the code

Run the Node server.js command again and access the browser to obtain data normally

POST sets the request body

Data of any type and format can be set as long as there is a corresponding processing method on the server side

Syntactically, the request size is very flexible; However, in actual usage scenarios, it is usually written in a specific format (such as JSON)

xhr.send('a=100&b=200&c=300');
Copy the code

AJAX sets the request header information


Predefined request headers

Request header information can be set after initialization but before the request is sent

xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
Copy the code

Custom request headers

In addition to the above predefined request headers, you can also set custom request headers

xhr.setRequestHeader('name'.'atguigu');
Copy the code

The view header information is already available

However, errors are reported because of the browser’s security mechanisms

We need to add a line of response header Settings in server.js

response.setHeader('Access-Control-Allow-Headers'.The '*');
Copy the code

But that alone doesn’t work. We notice that there is also an OPTIONS request method that validates the request header to see if it is available or not

We do not create routing rules for OPTIONS in server.js, so we cannot receive OPTIONS requests

We can use the post method instead of all, it can receive any type of request (GET/post/PUT/DELETE/PATCH/OPTIONS…).

app.all('/server'.(request, response) = > {
    // Set the response header to allow cross-domain
    response.setHeader('Access-Control-Allow-Origin'.The '*');
    // Set the response header to allow any type of header information
    response.setHeader('Access-Control-Allow-Headers'.The '*');
    // Set the response body
    response.send('Hello Express');
});
Copy the code

Restart the server.js service and check the network console. The status is normal

9. The server responds to JSON data


Change the contents of the send method in server.js. Note that this method can only receive strings and buffers, so it needs to be converted

const data = {
    name:'Hello Ajax'
}
let str = JSON.stringify(data);
response.send(str);
Copy the code

Js code

const result = document.getElementById('result');
window.onkeydown = function () {
    const xhr = new XMLHttpRequest();
    xhr.open('POST'.'http://127.0.0.1:8000/server-json');
    xhr.send();
    xhr.onreadystatechange = function () {
        if (this.readyState === 4 && this.status >= 200 && this.status < 300) {
            console.log(this.response);
            result.innerHTML = this.response; }}; }Copy the code

The effect

The above returned data is relatively simple and the contents are relatively easy to obtain. Once the results are more complex, it can be difficult to extract some data

This is where the returned results need to be processed

Manual data conversion

Since our server is returning json string content, the content type of Response is also a string

Using the JSON tool method, you can convert a JSON string into a JSON object

let response = this.response;
console.log(typeof response); // string
data = JSON.parse(response);
result.innerHTML = data.name;
Copy the code

Automatic data conversion

// Set the response body type
xhr.responseType = 'json';
Copy the code

The result is a JSON object that can be used without manual conversion

let response = this.response;
console.log(typeof response); // object
result.innerHTML = response.name;
Copy the code

10. Install the Nodemon automatic restart tool


  • Website address: www.npmjs.com/package/nod…
  • Installation command:npm install -g nodemon
  • Start command:nodemon xxx.jsalternativenode xxx.js
  • Advantages: You don’t have to modify the server code manually every timeshutdownRestart, but automatically restart every time we modify the code

11. Internet Explorer cache problem


After starting the project using Nodemon, modify the response body

This works fine in Chrome, with the second request being 200

This is because IE is not cached by default. We can see that the second network request status code is 304

How to solve the Internet Explorer browser cache problem?

The processing is as simple as adding a timestamp parameter to the code

Because the timestamp changes almost instantaneously, the parameters of each request will be different and the browser will treat it as a different request

xhr.open('GET'.'http://127.0.0.1:8000/server-ie? t' + Date.now());
Copy the code

Let’s look at the effect in IE

12. Request timeout and network exception


The request timeout

Modify server.js to set the delay for sending response packets

setTimeout(() = >{
    response.send('Hello Ajax');
}, 2000);
Copy the code

The effect

We have set a short delay for simulated timeouts, but in general, requests that take too long must be processed

If a request times out, a timeout notification is required to reduce the usage of network bandwidth resources and improve user experience

So how do you set the timeout information?

  • Timeout period:timeout
  • Timeout callback:ontimeout
// Set the timeout period
xhr.timeout = 1000;
// Set the timeout callback
xhr.ontimeout = () = > {
    alert('Request timed out! ');
};
Copy the code

The effect

You can see that the timeout callback is called when the request time exceeds the timeout we set and that the network request status changes to Canceled.

Network anomalies

Of course, in addition to the server response time caused by the request timeout, there may be due to our network speed or other network problems caused by the request failure

We can add an onError callback to handle such problems

// Set the network exception callback
xhr.onerror = () = > {
    alert("Network exception");
};
Copy the code

We made Chrome’s Web console offline to simulate a request in an offline environment

As you can see, a network exception has been prompted, that is, the onError callback has gone and the state has changed to (failed) net::ERR_INTERNET_DISCONNECTED

13. Manually cancel the request


  • abort()Method: Manually cancel the request
const btns = document.getElementsByTagName('button');
const btn1 = btns[0];
const btn2 = btns[1];

let xhr = null;
btn1.addEventListener('click'.() = > {
    xhr = new XMLHttpRequest();
    xhr.open('GET'.'http://127.0.0.1:8000/server-timeout');
    xhr.send();
});
btn2.addEventListener('click'.() = > {
    xhr.abort();
});
Copy the code

The effect

14. The request is sent repeatedly


If the server is relatively slow to respond and the user clicks the button frequently because they can’t get a response. Therefore, the browser will send a large number of repeated requests to the server in a short period of time, and the server will have to deal with these requests frequently, and the pressure on the server side will be very high

So what is the solution to the problem of repeated requests?

Before sending a request, check whether the same request is being processed before. If so, cancel the same request and send a new request. This ensures that only one request can be received at a time, thus reducing the strain on the server

const btns = document.getElementsByTagName('button');
let xhr = null;
// Identifies whether an AJAX request is being sent
let isSending = false;
btns[0].addEventListener('click'.() = > {
    // Cancel the request manually if the previous request has not been completed
    if (isSending) {
        xhr.abort();
    }
    xhr = new XMLHttpRequest();
    xhr.open('GET'.'http://127.0.0.1:8000/servertimeout');
    xhr.send();
    xhr.onreadystatechange = () = > {
        // After the request response is complete, modify the variable identifier
        if (xhr.readyState === 4) {
            isSending = true; }}; });Copy the code

The effect

As you can see, if the button is clicked frequently to initiate the same request, the previous request will be cancelled before each new request is initiated

JQuery sends AJAX requests


  • The jQuery script

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    Copy the code
  • Bootstrp script

    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.css" rel="stylesheet">
    Copy the code

A GET request

$.get(url,[data],[callback],[type])
Copy the code
  • url: Requested URL
  • data: Parameter to be carried by the request
  • callback: callback function on successful loading
  • type: Sets the returned content format, XML, HTML, script, ison, text, _default
btns.eq(0).click(() = > {
    $.get('http://127.0.0.1:8000/server-jquery', { a: 100.b: 200 }, (data) = > {
        console.log(typeof data, data); // object {name: "Hello jquery"}
    }, 'json');
});
Copy the code

A POST request

$.post(url,[data],[callback],[type])
Copy the code
  • url: Requested URL
  • data: Parameter to be carried by the request
  • callback: callback function on successful loading
  • type: Sets the returned content format, XML, HTML, script, ison, text, _default
btns.eq(1).click(() = > {
    $.post('http://127.0.0.1:8000/server-jquery', { a: 100.b: 200 }, (data) = > {
        console.log(typeof data, data); // string {name: "Hello jquery"}
    });
});
Copy the code

Common methods

$.ajax({
    // Request an address
    url: 'http://127.0.0.1:8000/server-jquery'.// Request parameters
    data: { a: 100.b: 200 },
    // Request type
    type: 'GET'.// Response body type
    dataType: 'json'.// Successful callback
    success: data= > {
        console.log(typeof data, data); // string {name: "Hello jquery"} Enable dataType: object {name: "Hello jquery"}
    },
    // The timeout period
    timeout: 1000.// Failed callback
    error: () = > {
        alert('Wrong');
    },
    / / headers
    headers: {
        c: 300.d: 400}});Copy the code

The error correction

Error Network status

Header information

16. Axios sends AJAX requests


  • Axios website: www.npmjs.com/package/axi…

A GET request

  • axios#get(url[,config])
  • The function returns onepromiseObject, withthenThe callback processing
axios.defaults.baseURL = 'http://127.0.0.1:8000/';
axios.get('server-axios', {
    // Request parameters
    params: {
        a: 100.b: 200
    },
    / / request header
    headers: {
        c: 300.d: 400
    }
}).then(value= > {
    console.log(value);
});
Copy the code

Request parameters, header information

Console information

A POST request

  • axios#post(url[,data[,config]])
axios.post('server-axios', {
    / / request body
    e: 500.f: 600
}, {
    // Request parameters
    params: {
        a: 100.b: 200
    },
    / / request header
    headers: {
        c: 300.d: 400
    }
}).then(value= > {
    console.log(value);
});
Copy the code

Header information

Request parameters, request body

Common methods

  • axios(url[, config])
axios({
    method: 'POST'.url: 'server-axios'.// Request parameters
    params: {
        a: 100.b: 200
    },
    / / request header
    headers: {
        c: 300.d: 400
    },
    / / request body
    data: {
        e: 500.f: 600
    },
    // Response body type
    dataType: 'json'
}).then(response= > {
    console.log(response.status); / / 200
    console.log(response.statusText); // OK
    console.log(response.headers); // {content-length: "22", content-type: "text/html; charset=utf-8"}
    console.log(typeof response.data, response.data); // object {name: "Hello axios"}
});
Copy the code

17. The fetch function sends AJAX requests


fetch('http://127.0.0.1:8000/server-fetch? a=100&b=100', {
    // Request method
    method: 'POST'./ / request header
    headers: {
        c: 300.d: 400
    },
    / / request body
    body: 'e=500&f=600'
}).then(response= > {
    console.log(response);
});
Copy the code

Request parameters, header information

Request body information

Console information

If we only want the response body content, we can modify the THEN callback

. .then(response= > {
    return response.text();
}).then(response= > {
    console.log(typeof response, response); // string {"name":"Hello fetch"}
});
Copy the code

If you specify that the response body is a JSON string, you can modify it as follows to return an Object object

. .then(response= > {
    return response.json();
}).then(response= > {
    console.log(typeof response, response); // object {"name":"Hello fetch"}
});
Copy the code

18. Cross-domain issues


The same-origin policy

The same-Origin Policy, first proposed by Netscape, is a security Policy for browsers

Same-origin: The protocol, domain name, and port number must be the same. Violating the same-origin policy means cross-domain

Server. The js code

const express = require('express');
const app = express();

app.get('/home'.(request, response) = > {
    // Respond to a page
    response.sendFile(__dirname + '/11- Same Origin policy. HTML ');
});
app.get('/data'.(request, response) = > {
    response.send('User data');
});

app.listen(9000.() = > {
    console.log("Service started, listening on port 9000...");
});
Copy the code

Js code

const xhr = new XMLHttpRequest();
// The url can be abbreviated because it satisfies the same origin policy
xhr.open('GET'.'/data');
xhr.send();
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
        console.log(xhr.response);// User data}};Copy the code

How to resolve cross-domain

JSONP

1) What is JSONP

JSONP (JSON with Padding) is an unofficial cross-domain solution, developed purely through the ingenuity of programmers, that supports only GET requests

2) How does JSONP work?

Some tags on web pages naturally have cross-domain capabilities, such as the IMG link Iframe script

For example, we introduced it before, and there was no error, so we can use it

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
Copy the code

JSONP takes advantage of the cross-domain capabilities of script tags to send requests

Let’s add the following to the HTML

<div id="result"></div>
<script>
    function handle(data) {
        const result = document.getElementById('result');
        result.innerHTML = data.name;
    }
</script>
<script src="./js/app.js"></script>
Copy the code

App. Js code

const data = {
    name: 'JSONP'
};
handle(data);
Copy the code

After we start the project using the live-server service, we can get the HTTP address corresponding to app.js

Let’s replace the SRC address of app.js

<script src="http://127.0.0.1:5500/12-JSONP/js/app.js"></script>
Copy the code

Can we view the SRC address of this script as the server method address?

The SRC address of jQuery and Axios is similar to the SRC address of jQuery and Axios, so we can write a routing rule on the server side

app.all('/server-jsonp'.(request, response) = > {
    response.send('hello jsonp'); 
});
Copy the code

Console error

Uncaught SyntaxError: Unexpected identifier
Copy the code

But if you look at the network response body, you actually get it

Because the script tag requires a JS script code, and now it gets a string of characters, which cannot be parsed

So we need to modify the server response content

const data = {
    name: 'JSONP'
};
let str = JSON.stringify(data);
The end method does not have a special response header
// To facilitate concatenation, use template strings
response.end(`handle(${str}) `); // The result is a function call
Copy the code

This time the content renders normally, the console does not report an error message, and the requested content is a string of JS code we wrote

3) Use of JSONP

The HTML code

User name:<input type="text" id="username">
<p></p>
<script>
    // Declare handle
    function handle(data) {
        var input = document.querySelector('input');
        input.style.border = "solid 1px #f00";
        // Modify the prompt text of the p tag
        var p = document.querySelector('p');
        p.innerHTML = data.msg;
    }
</script>
<script>
    const input = document.querySelector('input');
    input.onblur = () = > {
        let username = this.username;
        // create a script tag
        var script = document.createElement('script');
        // 2. Set the SRC attribute
        script.src = 'http://127.0.0.1:8000/check-username';
        // 3, insert script into the document
        document.body.appendChild(script);
    };
</script>
Copy the code

Server code

app.all('/check-username'.(request, response) = > {
    const data = {
        exist: 1.msg:'Username already exists'
    };
    let str = JSON.stringify(data);
    response.end(`handle(${str}) `); 
});
Copy the code

The effect

4) jQuery sends JSONP requests
$.getJSON(url,[data],[fn])
Copy the code
  • Url: address for sending requests
  • Data: key/value parameters to be sent
  • Callback: callback function when loading successfully

The HTML code

<button>Click Send request</button><br><br>
<div id="result"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $('button').eq(0).click(() = > {
        $.getJSON('http://127.0.0.1:8000/server-jsonp-jquery? callback=? '.data= >{$('#result').html(data.msg);
        });
    });
</script>
Copy the code

Server code

app.all('/server-jsonp-jquery'.(request, response) = > {
    const data = {
        exist: 1.msg:'Username already exists'
    };
    let str = JSON.stringify(data);
    response.end(` (${str}) `);
});
Copy the code

There is no output at this point, but a callback argument is automatically generated in the request parameters

Since we are now accessing port 8000 of the Nodemon service through port 5500 of the live-server service, it is now cross-domain access

So we need to return a JAVASCRIPT code, but we need to return a string as a result, how to do?

According to jSONP native code thinking, we must return a JS script code

This is where the callback argument comes in, and we need to modify the server code

// Receive the callback argument
var cb = request.query.callback;
response.end(`${cb}(${str}) `); 
Copy the code

The effect

We can see that the response body has automatically retrieved the callback argument and the server has returned the result

CORS

  • Official website: developer.mozilla.org/zh-CN/docs/…
1) What is CORS?

Cross-origin Resource Sharing (CORS) : Cross-domain Resource Sharing. CORS is the official cross-domain solution, which does not need to do any special operations in the client side, completely processed in the server, support get and POST requests. Cross-domain resource sharing standards have added a new set of HTTP header fields that allow servers to declare which sources have access to which resources through browsers

2) How does CORS work?

CORS sets a response header to tell the browser that the request is cross-domain and the browser will allow the response after receiving it

3) Use of CORS

The HTML code

<button>Click Send request</button><br><br>
<div id="result"></div>
<script>
    const btn = document.getElementsByTagName('button') [0];
    const result = document.querySelector('#result');
    btn.addEventListener('click'.function () {
        const xhr = new XMLHttpRequest();
        xhr.open('GET'.'http://127.0.0.1:8000/server-cors');
        xhr.send();
        xhr.onreadystatechange = function () {
            if (this.readyState === 4 && this.status >= 200 && this.status < 300) {
                result.innerHTML = this.response; }}; });</script>
Copy the code

Server code

app.all('/server-cors'.(request, response) = > {
    response.send('Hello cors');
});
Copy the code

The effect

To make a cross-domain request, we must set the response header that allows cross-domain when the server returns the result

// Set the response header to allow cross-domain
response.setHeader('Access-Control-Allow-Origin'.The '*');
Copy the code

In addition, there are some HTTP response header fields

5) HTTP response header field
HTTP response header field role
Access-Control-Allow-Origin Specifies the outer domain URI that allows access to the resource
Access-Control-Expose-Headers Tell the server to whitelist headers that are accessible to the browser
Access-Control-Max-Age Specifies how long the results of a preflight request can be cached
Access-Control-Allow-Credentials Whether to allow the browser to read the content of the response
Access-Control-Allow-Methods Specifies the HTTP methods allowed for the actual request
Access-Control-Allow-Headers Specifies the header field allowed in the actual request

We generally use it this way, allowing cross-domain, with custom header information, arbitrary methods

response.setHeader("Access-Control-Allow-Origin"."*"); 
response.setHeader("Access-Control-Allow-Headers"."*"); 
response.setHeader("Access-Control-A1low-Method"."*"); 
Copy the code