current position:Home>Ajax learning notes

Ajax learning notes

2022-04-29 08:10:19Chen Chen is trying

One 、Ajax brief introduction

AJAX brief introduction AJAX Its full name is Asynchronous JavaScript And XML, It's asynchronous JS and XML.

adopt AJAX You can send asynchronous requests to the server in the browser , The biggest advantage : No refresh to get data .

AJAX It's not a new programming language , It's a combination of existing standards New way .

1、XML brief introduction

  1. XML Extensible markup language .
  2. XML Designed to transmit and store data .
  3. XML and HTM L similar , The difference is HTML Are predefined labels in , and XML There are no predefined labels in , It's all custom labels , Used to represent some data .

For example, I have a student data :

name = “ The Monkey King ” ; age = 18 ; gender = “ male ” ;

 use  XML  Express :
<student>
<name> The Monkey King </name>
<age>18</age>
<gender> male </gender>
</student>

Now it has been JSON To replace the .

{"name":" The Monkey King ","age":18,"gender":" male "}

2、Ajax Characteristics

Ⅰ-AJAX The advantages of

  1. You can communicate with the server without refreshing the page .

  2. Allows you to update some page content according to user events .

Ⅱ-Ajax The shortcomings of

  1. No browsing history , Can't back

  2. There are cross-domain problems ( Homology )

  3. SEO 【 Search engine 】 unfriendly

3、HTTP brief introduction

HTTP(hypertext transport protocol) agreement 『 Hypertext transfer protocol 』, The protocol specifies the rules of communication between browser and World Wide Web server . Appointment ,、 The rules

Ⅰ- Request message

The focus is on format and parameters

  • Request line
  • Request type :GET、POST
  • url route
  • HTTP Protocol version
  • Request header
  • Format :
    • Host: atguigu.com
    • Cookie: name=guigu
    • Content-type: aplication/x-www-form-urlencoded
    • User-Agent: chrome 83
  • Request a blank line 【 There must be 】
  • Request body
  • If it is get request , Request body is empty
  • If it is post request , The request body can be empty or not
// complete http Request message 
 That's ok    POST /s?ie=utf-8 HTTP/1.1 

 head    Host: atguigu.com
​    Cookie: name=guigu
​    Content-type: application/x-www-form-urlencoded
​    User-Agent: chrome 83
 Blank line 
 body    username=admin&password=admin

Ⅱ- response message

  • Response line
  • HTTP Protocol version
  • Response status code :200、404、403、500、401 etc.
  • Response status string : Same as status code
  • Response head
  • Format
    • Content-Type:text/html;charset=utf-8
    • Content-length:2048
    • Content-encoding:gzip
  • Respond to blank lines : There has to be
  • Response body : Main contents of response
// complete HTTP response message 
 That's ok    HTTP/1.1 200 OK

 head    Content-Type: text/html;charset=utf-8
​    Content-length: 2048
​    Content-encoding: gzip
 Blank line   
 body    <html><head></head><body><h1> Silicon Valley </h1></body></html>

Ⅲ-Chrome Check the communication message on the network console

1、Network --> Hearders Request header

2、Network --> Response Response body : Usually it returns html

Two 、 Native Ajax

1、XMLHttpRequest,AJAX All operations of are performed through this object .

2、 When you want to set a custom request header , You need to set the response header at the back end

// Indicates receiving any type of request  
app.all('/server', (request, response) => {
      // Response head   Allow cross-domain   Run custom response header 
response.setHeader('Access-Control-Allow-Origin', '*'); response.setHeader('Access-Control-Allow-Headers', '*');}

3、ajax Request status :xhr.readyState

Response status code :

  • ​ 0: Request not initialized , Not called yet open().

  • ​ 1: The request has been established , But it hasn't been sent yet , Not called yet send().

  • ​ 2: Request sent , Processing ( Usually now you can get the content header from the response ).2 It starts with success

  • ​ 3: The request is being processed ; Usually some data is available in the response , It's not all done .

  • ​ 4: Response completed ; You can get and use the server's response

〇-Ajax Use

Use steps :

1)  establish  XMLHttpRequest  object 
var xhr = new XMLHttpRequest();
2)  Set request information 
xhr.open(method, url);
// You can set the request header , Generally not set 
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
3)  Send a request 
xhr.send(body) //get  Request not to transmit  body  Parameters , Only  post  Request to use 
4)  Receiving response 
//xhr.responseXML  receive  xml  Response data in format 
//xhr.responseText  The format of the response data 
xhr.onreadystatechange = function (){
     
if(xhr.readyState == 4 && xhr.status == 200){
     
var text = xhr.responseText;
console.log(text);
}}

Ⅰ-Get The way

    // The binding event 
    btn.onclick = function () {
    
      //1.  Create objects 
      const xhr = new XMLHttpRequest();
      //2.  initialization   Set the request method and  url
      xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
      //3.  send out 
      xhr.send();
      //4.  Event binding   Process the result returned by the server 
      // on when  When .... When 
      // readystate  yes  xhr  Properties in objects ,  According to state  0 1 2 3 4
      // change  change 
      xhr.onreadystatechange = function () {
    
        // Judge  ( The server returns all the results )
        if (xhr.readyState === 4) {
    
          // Determine the response status code  200 404 403 401 500
          // 2xx  success 
          if (xhr.status >= 200 && xhr.status < 300) {
    
            // Processing results   That's ok   head   Blank line   body 
            // Respond to  
            // console.log(xhr.status);// Status code 
            // console.log(xhr.statusText);// Status string 
            // console.log(xhr.getAllResponseHeaders());// All response headers 
            // console.log(xhr.response);// Response body 
            // Set up  result  The text of 
            result.innerHTML = xhr.response;
          } else {
    }
        }
      }
    }

Ⅱ-Post The way

     // The binding event 
        result.addEventListener("mouseover", function(){
    
            //1.  Create objects 
            const xhr = new XMLHttpRequest();
            //2.  initialization   Set the type and  URL
            xhr.open('POST', 'http://127.0.0.1:8000/server');
            // Set request header 
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.setRequestHeader('name','atguigu');
            //3.  send out 
            xhr.send('a=100&b=200&c=300');
            // xhr.send('a:100&b:200&c:300');
            // xhr.send('1233211234567');
            //4.  Event binding 
            xhr.onreadystatechange = function(){
    
                // Judge 
                if(xhr.readyState === 4){
    
                    if(xhr.status >= 200 && xhr.status < 300){
    
                        // Process the result returned by the server 
                        result.innerHTML = xhr.response;
                    }
                }
            }
        });

Ⅲ- solve ie The cache problem

problem : In some browsers (IE), because Caching mechanisms The existence of ,ajax Only the first request will be sent , The remaining multiple requests will not be sent to the browser, but directly load the data in the cache .

Solution : The browser cache is based on url Address to record , So we just need to modify url Address To avoid cache problems xhr.open("get","/testAJAX?t="+Date.now());

Ⅳ- Request timeout and network exception

When your request takes too long , Or when there is no network , The corresponding treatment

   btn.addEventListener('click', function(){
    
            const xhr = new XMLHttpRequest();
            // timeout  2s  Set up 
            xhr.timeout = 2000;
            // Timeout callback 
            xhr.ontimeout = function(){
    
                alert(" Network anomalies ,  Please try again later !!");
            }
            // Network exception callback 
            xhr.onerror = function(){
    
                alert(" There seems to be something wrong with your network !");
            }

            xhr.open("GET",'http://127.0.0.1:8000/delay');
            xhr.send();
            xhr.onreadystatechange = function(){
    
                if(xhr.readyState === 4){
    
                    if(xhr.status >= 200 && xhr.status< 300){
    
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })

Ⅴ- Cancel the request

After the request is sent But the response did not complete You can cancel the request

        const btns = document.querySelectorAll('button');
        let x = null;
        btns[0].onclick = function(){
    
            x = new XMLHttpRequest();
            x.open("GET",'http://127.0.0.1:8000/delay');
            x.send();
        }
        // abort
        btns[1].onclick = function(){
    
            x.abort();
        }

Ⅵ- Repeat request question

Before using Ⅴ Cancel the request for knowledge points , When I click, judge whether the previous request is being sent , If it is , Then stop the request

   btns[0].onclick = function(){
    
            // Determine the identification variable 
            if(isSending) x.abort();//  If you are sending ,  Then cancel the request ,  Create a new request 
            x = new XMLHttpRequest();
            // modify   Identifies the value of the variable 
            isSending = true;
            x.open("GET",'http://127.0.0.1:8000/delay');
            x.send();
            x.onreadystatechange = function(){
    
                if(x.readyState === 4){
    
                    // Modify the identification variable 
                    isSending = false;
                }
            }
        }

3、 ... and 、 There are three common Ajax Request mode

1、jQuery send out AJAX request

jQuery There are three ways to send requests :

When you simply request data , You can directly use the first two methods to request , When you need to set more things , have access to $.ajax() Method

Ⅰ-$.get()

  $('button').eq(0).click(function(){
    
            $.get('http://127.0.0.1:8000/jquery-server', {
    a:100, b:200}, function(data){
    
                console.log(data);
            },'json');
        });

Ⅱ-$.post()

  $('button').eq(1).click(function(){
    
            $.post('http://127.0.0.1:8000/jquery-server', {
    a:100, b:200}, function(data){
    
                console.log(data);
            });
        });

Ⅲ-$.ajax

   $('button').eq(2).click(function(){
    
            $.ajax({
    
                //url
                url: 'http://127.0.0.1:8000/jquery-server',
                // Parameters 
                data: {
    a:100, b:200},
                // Request type 
                type: 'GET',
                // Response body results 
                dataType: 'json',
                // Successful callback 
                success: function(data){
    
                    console.log(data);
                },
                // Timeout time 
                timeout: 2000,
                // Failed callback 
                error: function(){
    
                    console.log(' Error !!');
                },
                // Header information 
                headers: {
    
                    c:300,
                    d:400
                }
            });
        });

2、Axios send out AJAX request

Ⅰ-axios.get()

axios.get(url,data,params)

  // To configure  baseURL
    axios.defaults.baseURL = 'http://127.0.0.1:8000';

    btns[0].onclick = function () {
    
      //GET  request 
      axios.get('/axios-server', {
    
        //url  Parameters 
        params: {
    
          id: 100,
          vip: 7
        },
        // Request header information 
        headers: {
    
          name: 'atguigu',
          age: 20
        }
      }).then(value => {
    
        console.log(value);
      });
    }

Ⅱ-axios.get()

axios.post(url,data,params)

  // To configure  baseURL
    axios.defaults.baseURL = 'http://127.0.0.1:8000';  
	btns[1].onclick = function () {
    
      axios.post('/axios-server', {
    
        username: 'admin',
        password: 'admin'
      }, {
    
        //url 
        params: {
    
          id: 200,
          vip: 9
        },
        // Request header parameters 
        headers: {
    
          height: 180,
          weight: 180,
        }
      });
    }

Ⅲ-axios() Commonly used

axios({})

  // To configure  baseURL
    axios.defaults.baseURL = 'http://127.0.0.1:8000';
	btns[2].onclick = function () {
    
      axios({
    
        // Request method 
        method: 'POST',
        //url
        url: '/axios-server',
        //url Parameters 
        params: {
    
          vip: 10,
          level: 30
        },
        // Header information , If you use custom header information in this section , The server needs to be modified accordingly , Normal not set 
        headers: {
    
          a: 100,
          b: 200
        },
        // Request body parameters 
        data: {
    
          username: 'admin',
          password: 'admin'
        }
      }).then(response => {
    
        // Response status code 
        console.log(response.status);
        // Response status string 
        console.log(response.statusText);
        // Response header information 
        console.log(response.headers);
        // Response body 
        console.log(response.data);
      })
    }

3、Fetch send out AJAX request

Code example

  btn.onclick = function () {
    
      fetch('http://127.0.0.1:8000/fetch-server?vip=10', {
    
        // Request method 
        method: 'POST',
        // Request header 
        headers: {
    
          name: 'atguigu'
        },
        // Request body 
        body: 'username=admin&password=admin'
      }).then(response => {
    
        // return response.text();
        return response.json();
      }).then(response => {
    
        console.log(response);
      });
    }

Four 、 Cross domain and solution

1、 What is crossing ?
  • One web page to another different domain name / Different protocols / Web page request resources of different ports , This is cross domain .
  • Cross domain causes : In the current domain name request website , It is not allowed to pass by default ajax Request to send another domain name .
2、 Why cross domain requests ?
  • Because browsers use the same origin strategy
3、 What is homology strategy ?
  • The homologous strategy is Netscape A well-known security policy proposed , All support now JavaScript All browsers of will use this strategy . Homology policy is the core and basic security function of browser , If there is no homology strategy , The normal function of the browser may be affected . so to speak web It's built on the same origin strategy , The browser is simply an implementation of the same origin policy .
  • Homology : agreement 、 domain name 、 Port number It must be exactly the same . Violating the homology strategy is cross domain .
4、 Why do browsers use the same origin strategy ?
  • To ensure the information security of users , Prevent malicious websites from stealing data , If the pages do not meet the requirements of homology , Will not be able to :
    1. share Cookie、LocalStorage、IndexDB
    2. obtain DOM
    3. AJAX Request cannot be sent
5、 Five solutions across domains :

​ 1、 Front end use jsonp ( It is not recommended to use )

​ 2、 backstage Http Request forwarding

​ 3、 Background configuration is homologous Cors ( recommend )

​ 4、 Use SpringCloud gateway

​ 5、 Use nginx Do the forwarding ( recommend )

Two of them are mentioned in this course :

1、jsonP

1)JSONP What is it? ?

​ JSONP(JSON with Padding), Is an unofficial cross domain solution , Rely solely on the ingenuity of programmers Intelligence developed , Only support get request .

2)JSONP How does it work ?

​ Some tags on Web pages are inherently cross domain , such as :img link iframe script. JSONP Is the use script Tag's cross domain capability to send requests .

Ⅰ-jsonP Use

   // 1.  Create a dynamic  script  label ------------------------------------------------------------
    var script = document.createElement("script");
	//2.  Set up  script  Of  src,  Set the callback function 
    script.src = "http://localhost:3000/testAJAX?callback=abc";
    function abc(data) {
    
      alert(data.name);
    };
   // 3.  take  script  Add to  body  in 
    document.body.appendChild(script);

   // 4.  Processing of routing in the server ------------------------------------------------------
    router.get("/testAJAX", function (req, res) {
    
      console.log(" Receive a request ");
      var callback = req.query.callback;
      var obj = {
    
        ame: " The Monkey King ",
        age: 18
      }
      res.send(callback + "(" + JSON.stringify(obj) + ")");
    });

Ⅱ-jQuery send out jsonP request

// The front-end code -----------------------------------------------------------------------------------
$('button').eq(0).click(function () {
    
  $.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?', function (data) {
    
    $('#result').html(`  name : ${
      data.name}<br>  Campus : ${
      data.city} `)
  });
});

// Server code -----------------------------------------------------------
app.all('/jquery-jsonp-server', (request, response) => {
    
  // response.send('console.log("hello jsonp")');
  const data = {
    
    name: ' Silicon Valley ',
    city: [' Beijing ', ' Shanghai ', ' Shenzhen ']
  };
  // Convert data to a string 
  let str = JSON.stringify(data);
  // receive  callback  Parameters 
  let cb = request.query.callback;

  // Return results 
  response.end(`${
      cb}(${
      str})`);
});

Ⅲ- Develop encapsulated jsonP plug-in unit

1、 cost : Front and rear end linkage is required

2、 quintessence : The method name is automatically generated by the plug-in , And dynamically generate functions on the current page , Then call the callback function reserved by the user in the generated function

3、 plug-in unit : Automated de simulation is based on script The process of implementing cross domain requests ( It's a black box for users )

4、 Parameter splicing :url It's already with parameters . And without reference

5、id Optimize Well, you can add a container to manage id

1、 The front-end call test is encapsulated jsonP Code

// Test call function 
    let test=function () {
    
        jsonP.req({
    
            url:"http://localhost:3000/jsonpx",
            data:{
    
                a:"111"
            },
            callback:function (result) {
    
                alert(" success "+result)
            }
        })
    }

2、 Server side test code

router.get('/jsonpx', async function (req, resp, next) {
    
    let callback=req.query.callback;
    let data=req.query.a;
    if (!data){
    
        resp.send(`${
      callback}(' Hong jl: I'm the server code ')`)
    }
    resp.send(`${
      callback}(' Hong jl: I'm the server code `+data+`')`)
})

3、 Encapsulate native code

<script>
    /**author:@hongjilin * 1. Make a statement jsonP Plug in object  *  effect : Separate scopes  */
    let jsonP = {
    };

    /** *2. Create two arrays of name alternates in the plug-in object  */
    jsonP.char = {
    
        Number: '0123456789',
        Letter: 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
    }
    /** *  Through random number extraction, spare character array library patching function id * @param charLen * @param numLen */
    jsonP.newFunId = function (charLen, numLen) {
    
        let id = '';
        for (let i = 0; i < charLen; i++) {
    
            id += this.char.Letter.charAt(Math.random() * 52)
        }
        for (let j = 0; j < numLen; j++) {
    
            id += Math.floor(Math.random() * 10);
        }
        return id;
    }
    /** *  Splicing path  * @param url * @param key * @param value */
    jsonP.jointUrl = function (url, key, value) {
    
        if (url && key && value) {
    
            let sign = "&"
            // If it's the first time 
            if (url.indexOf('?') == -1) {
    
                sign = '?'
            }

            url += sign + key + "=" + value
        }
        return url;
    }
    /**  encapsulation err Attribute convenience  */
    jsonP.err = function (msg) {
    
        console.error(msg)
    }

    /** *  Send request function  * @param options */
    jsonP.req = function (options) {
    
        let jsonId={
    };
        //1. Generate method name 
        jsonId.funId = this.newFunId(4,8);
        let Userurl = options.url;
        let Userdata = options.data;
        if (!options) {
    
            this.err(" The input cannot be empty ")
            return;
        } else if (!Userurl) {
    
            this.err("url Can't be empty ")
            return;
        } else if (!Userdata) {
    
            // without data, initialization 
            Userdata = {
    };
        }
        // Assign the function name to userdata In the callback function property of 
        Userdata.callback = jsonId.funId;
        for (let key in Userdata) {
    
            Userurl = this.jointUrl(Userurl, key, Userdata[key])
        }
        let script = document.createElement('script');
        script.setAttribute("id" , jsonId.funId);
        script.setAttribute("src" , Userurl);
        // Dynamically generated functions 
        let callback=function (result) {
    
            console.log("xxxxxxx")
            // Business logic callback 
            if (options.callback){
    
                try {
    
                    options.callback(result)
                }catch (e) {
    
                    this.err(e.message)
                }
            }
            // aftermath 
            let tmp=document.getElementById(jsonId.funId)
            tmp.parentNode.removeChild(tmp);
            eval(jsonId.funId+'=null')
        }
        eval("window."+jsonId.funId+"=function(result){ callback(result) }")
        document.head.appendChild(script)

    }
</script>

2、CORS

1、CORS Document links

2、CORS What is it? ?

​ CORS(Cross-Origin Resource Sharing), Cross-domain resource sharing .CORS Is the official cross domain solution case , Its characteristic is that it does not need to do any special operation on the client , Completely processed in the server , Support get and post request . A new set of standards for cross domain resource sharing has been added HTTP Header field , Allow the server to declare which What resources does the origin site have access to through the browser

3、CORS How does it work ?

​ CORS It tells the browser by setting a response header , The request allows cross domain , The browser received the response The response will be released later .

Ⅰ- Code example

app.all('/cors-server', (request, response) => {
    
  // Set the response header 
    // The response header can carry a  Access-Control-Allow-Origin  Field 
  response.setHeader("Access-Control-Allow-Origin", "*");
    //Access-Control-Allow-Headers  The header field is used for the response to the preview request . It indicates the first word allowed in the actual request 
  response.setHeader("Access-Control-Allow-Headers", '*');
    //Access-Control-Allow-Methods  The header field is used for the response to the preview request . It indicates what... The actual request allows  HTTP
  response.setHeader("Access-Control-Allow-Method", '*');
  // response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
  response.send('hello CORS');
});

Ⅱ-HTTP Response first field

This section lists the response header fields defined by the specification . In the previous section , We've seen how these header fields work in real scenarios .

1、Access-Control-Allow-Origin

The response header can carry a Access-Control-Allow-Origin Field , The syntax is as follows :

Access-Control-Allow-Origin: <origin> | *

among ,origin The value of the parameter specifies the foreign domain that is allowed to access the resource URI. For requests that do not need to carry identity credentials , The server can specify that the value of this field is a wildcard , Indicates that requests from all domains are allowed .

for example , The following field values will be allowed to come from http://mozilla.com Request :

Access-Control-Allow-Origin: http://mozilla.com

If the server specifies a specific domain name instead of “*”, So in response to the header Vary The value of the field must contain Origin. This will tell the client : The server returns different content to different origin sites .

2、Access-Control-Expose-Headers

translator's note : When accessing across sources ,XMLHttpRequest Object's getResponseHeader() Method can only get some basic response headers ,Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma, If you want to visit other headers , The server is required to set the response header .

Access-Control-Expose-Headers The header lets the server put the header that the browser is allowed to access into the white list , for example :

Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header

So the browser can go through getResponseHeader visit X-My-Custom-Header and X-Another-Custom-Header Response header .

3、Access-Control-Max-Age

Access-Control-Max-Age The head designated preflight How long can the requested results be cached , Please refer to the above mentioned in this article preflight Example .

Access-Control-Max-Age: <delta-seconds>

delta-seconds parameter preflight How many seconds is the result of the request valid .

4、Access-Control-Allow-Credentials

Access-Control-Allow-Credentials The header specifies the browser credentials Set to true Whether to allow browser to read response The content of . When used on preflight Pre detect the response of the request , It specifies whether the actual request can be used credentials. Please note that : Simple GET The request will not be pre checked ; If this field is not included in the response to such a request , This response will be ignored , And the browser will not return the corresponding content to the web page .

Access-Control-Allow-Credentials: true

5、Access-Control-Allow-Methods

Access-Control-Allow-Methods The header field is used for the response to the preview request . It indicates what... The actual request allows HTTP Method .

Access-Control-Allow-Methods: <method>[, <method>]*

6、Access-Control-Allow-Headers

Access-Control-Allow-Headers The header field is used for the response to the preview request . It indicates the first field allowed in the actual request .

Access-Control-Allow-Headers: <field-name>[, <field-name>]*

Ⅲ-HTTP Request first field

This section lists the header fields that can be used to initiate cross source requests . Please note that , These first fields do not need to be set manually . When developers use XMLHttpRequest Object to initiate a cross source request , They're set up .

1、Origin

Origin The header field indicates the origin of the pre check request or the actual request .

Origin: <origin>

origin The value of the parameter is origin URI. It doesn't contain any path information , Just the server name .

Note: Sometimes it is useful to set the value of this field to an empty string , for example , When the origin is a data URL when .

Be careful , In all access control requests (Access control request) in ,Origin Header field Always Be sent

2、Access-Control-Request-Method

Access-Control-Request-Method The header field is used for pre inspection requests . Its effect is , What will be used by the actual request HTTP Method to tell the server .

Access-Control-Request-Method: <method>

3、Access-Control-Request-Headers

Access-Control-Request-Headers The header field is used for pre inspection requests . Its effect is , Tell the server the first field carried by the actual request .

Access-Control-Request-Headers: <field-name>[, <field-name>]*

5、 ... and 、 Server code example

The server code matching the above front-end code

//1.  introduce express
const express = require('express');

//2.  Create application objects 
const app = express();

//3.  Create routing rules 
// request  It is the encapsulation of request message 
// response  It is the encapsulation of response message 
app.get('/server', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  // Set the response body 
  response.send('HELLO AJAX - 2');
});

// Can receive any type of request  
app.all('/server', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  // Response head 
  response.setHeader('Access-Control-Allow-Headers', '*');
  // Set the response body 
  response.send('HELLO AJAX POST');
});

//JSON  Respond to 
app.all('/json-server', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  // Response head 
  response.setHeader('Access-Control-Allow-Headers', '*');
  // Respond to a data 
  const data = {
    
    name: 'atguigu'
  };
  // String conversion of objects 
  let str = JSON.stringify(data);
  // Set the response body 
  response.send(str);
});

// in the light of  IE  cache 
app.get('/ie', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  // Set the response body 
  response.send('HELLO IE - 5');
});

// Delayed response 
app.all('/delay', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Headers', '*');
  setTimeout(() => {
    
    // Set the response body 
    response.send(' Delayed response ');
  }, 1000)
});

//jQuery  service 
app.all('/jquery-server', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Headers', '*');
  // response.send('Hello jQuery AJAX');
  const data = {
    
    name: ' Silicon Valley '
  };
  response.send(JSON.stringify(data));
});

//axios  service 
app.all('/axios-server', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Headers', '*');
  // response.send('Hello jQuery AJAX');
  const data = {
    
    name: ' Silicon Valley '
  };
  response.send(JSON.stringify(data));
});

//fetch  service 
app.all('/fetch-server', (request, response) => {
    
  // Set the response header   Set allow cross domain 
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Headers', '*');
  // response.send('Hello jQuery AJAX');
  const data = {
    
    name: ' Silicon Valley '
  };
  response.send(JSON.stringify(data));
});

//jsonp service 
app.all('/jsonp-server', (request, response) => {
    
  // response.send('console.log("hello jsonp")');
  const data = {
    
    name: ' Silicon Valley atguigu'
  };
  // Convert data to a string 
  let str = JSON.stringify(data);
  // Return results 
  response.end(`handle(${
      str})`);
});

// User name detection exists 
app.all('/check-username', (request, response) => {
    
  // response.send('console.log("hello jsonp")');
  const data = {
    
    exist: 1,
    msg: ' The user name already exists '
  };
  // Convert data to a string 
  let str = JSON.stringify(data);
  // Return results 
  response.end(`handle(${
      str})`);
});

//
app.all('/jquery-jsonp-server', (request, response) => {
    
  // response.send('console.log("hello jsonp")');
  const data = {
    
    name: ' Silicon Valley ',
    city: [' Beijing ', ' Shanghai ', ' Shenzhen ']
  };
  // Convert data to a string 
  let str = JSON.stringify(data);
  // receive  callback  Parameters 
  let cb = request.query.callback;

  // Return results 
  response.end(`${
      cb}(${
      str})`);
});

app.all('/cors-server', (request, response) => {
    
  // Set the response header 
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Headers", '*');
  response.setHeader("Access-Control-Allow-Method", '*');
  // response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
  response.send('hello CORS');
});

//4.  Listening port starts service 
app.listen(8000, () => {
    
  console.log(" Service started , 8000  Port monitoring ....");
});

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290810140992.html

Random recommended