Nodejs__code__streamline__Ajax interaction

Introduction:

Full name Ajax (Asynchronous Javascript And XML)
Function

1. Update content without refreshing the page

2. A method of communication between the browser and the server

Commonly used parameters:

XMLHttpRequest

A constructor used to implement asynchronous communication between the browser and the server

Example: let xhr=new XMLHttpRequest()

readyState

Represents the status of XMLHttpRequest

0

Not initialized, open() has not been called yet

1

Start, open() has been called, but send() has not yet been called

2

Send, send() has been called, but the response has not been received yet

3

Receive, partial response data has been received

4

Completed, all response data has been received and can be used in the browser

response

Get any type of response data

responseText

Get response data of string type

responseType

Set the type of response data

timeout

Set the request timeout, the unit is ms

status

Indicates HTTP status code, 200 webpage…ok

statusText

Indicates HTTP status code description

withCredentials

Specify whether to carry cookies when sending requests using ajax

open

Set the type of request, URL and whether to process the request asynchronously

send

send request

abort

Terminate current request

setRequestHeader

Set the request header information, where the Content-type field tells the server the data format

Set the data sent to be the default submission data format of the form:

Example:xhr.setRequestHeader(‘Content-type’,’application/x-www-form-urlencoded’)

onreadystatechange

When readyState changes, the onreadystatechange event is triggered.

Code example:

Simple communication between browser and server

Front-end file: index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <h1>Ajax interaction</h1>
    <button id="bt_get">GetTest</button>
    <button id="bt_post">Post test</button>
    <script>
      const bt_get = document.getElementById("bt_get");
      const bt_post = document.getElementById("bt_post");
      var jx = {
        type: "POST",
        url: "http://127.0.0.1:80/",
        data: { name: "abc", move: "movie" },
        dataType: "json",
        async: true,
        success: function () {
          console.log("is ok...");
        },
        error: function () {
          alert("Error: Not a POST or GET request");
        },
      };
      function paramGroup(data) {
        let arr = [];
        for (let i in data) {
          arr.push(i + "=" + data[i]);
        }
        return arr.join(" & amp;");
      }
      function ajaxFc(obj) {
        var xhr = null,
          str = paramGroup(obj.data);
        //Create xhr
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else {
          xhr = new ActiveXObject("Microsoft,XMLHTTP");
        }
        console.log(obj.type.toLowerCase());
        if (obj.type.toLowerCase() === "get" & amp; & amp; obj.data !== undefined) {
          let url = obj.url + "?" + str;
          xhr.open(obj.type, url, obj.async || true);
          xhr.send(null);
        } else if (
          obj.type.toLowerCase() === "post" & amp; & amp;
          obj.data !== undefined
        ) {
          xhr.open(obj.type, obj.url, obj.async || true);
          xhr.setRequestHeader(
            "Content-type",
            "application/x-www-form-urlencoded"
          );
          xhr.send(str);
        } else {
          obj.error();
          return false;
        }
        //Event binding processes the results returned by the server
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 & amp; & amp; xhr.status === 200) {
            let res = xhr.responseText;
            try {
              if (typeof res === "object" || typeof res === "string") {
                alert(res);
              } else if (obj.dataType === "json") {
                console.log("json data");
              } else {
                throw new Error();
              }
            } catch (e) {
              throw new Error();
            }
          }
        };
      }
      bt_get.onclick = function () {
        jx.type = "get";
        jx.url = "http://127.0.0.1:80/api/get";
        ajaxFc(jx);
      };
      bt_post.onclick = function () {
        jx.type = "post";
        jx.url = "http://127.0.0.1:80/api/post";
        ajaxFc(jx);
      };
    </script>
  </body>
</html>

Backend file: index.js

const express = require('express');
const e = express();
e.get('/api/get', (req, res) => {
    res.send('Get ....Ok');
});
e.post('/api/post', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.send('Post ....Ok');
});
e.listen(80, function () {
    console.log('Server running at 127:0.0.1:80');
}); 

Code running

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Vue entry skill treeNode.js and npmNode installation and configuration 39640 people are learning the system