catalogue
1. How to read the local variables inside the function from the outside?
32. Front back separation - data interaction
(1) Data interface specification process
(5) Message board - writing method of the fifth issue
21. Recursion
(1) Case 1:
Recursion mode: 5 + 4 + 3 + 2 + 1
(2) Case 2:
var data = [ { name:'IT internet', child:[ {name:'Editing language',child:[{name:'java'},{name:'c#/.net'},{name:'python'}, {name:'Front end development',child:[{name:'jq'},{name:'vue'},{name:'react'}]}]}, {name:'Mobile development',child:[{name:'android development'},{name:'IOS development'}]}, {name:'Game development',child:[{name:'phaser Game development'},{name:'webGL Game development',child:[{name:'3D game'},{name:'2D game'}]}]} ] }, { name:'Design creation', child:[{name:'Graphic Artist Designer',child:[{name:'E-commerce Art'},{name:'Comprehensive graphic design'},{name:'Post photography'}]}, {name:'UI Design',child:[{name:'Interaction design'},{name:'webUI Design'},{name:'game UI Design'}]}, {name:'software design '}] }, { name:'Postgraduate entrance examination', child:[{name:'Postgraduate entrance examination'},{name:'university'},{name:'high school'},{name:'junior high school'}] }, { name:'Textual research on Vocational Enterprises', child:[{name:'civil servant',child:[{name:'Teacher examination'},{name:'architectural engineering'}]}] }];
Mode 1:
window.onload = function(){ var str = "<ul>"; for(var i=0;i<data.length;i++){ str+="<li>"+data[i].name+"</li>"; if(data[i].child){ str += "<ul>"; for(var j=0;j<data[i].child.length;j++){ str+="<li>"+data[i].child[j].name+"</li>"; } str += "</ul>"; } } str += "</ul>"; document.querySelector(".lists").innerHTML = str; }
Method 2: recursion
window.onload = function(){ //recursion function tree(data) { var str = "<ul>" for (var i = 0; i < data.length; i++) { str += "<li>" + data[i].name + "</li>" if (data[i].child) { //=====================================Replace with========================================= str += tree(data[i].child) //=================================================================================== } } str += "</ul>" //=====================================Add========================================= return str //=================================================================================== } document.querySelector(".lists").innerHTML = tree(data)
//The amount of code is reduced and the directory structure is clearer
22. Closure
(1) Understand
The special feature of javascript language is that global variables can be read directly inside the function, but local variables inside the function cannot be read outside the function.
function f1(){ var a=10; function f2(){ alert(a); } }
1. How to read the local variables inside the function from the outside?
Sometimes we need to get the local variables inside the function, which is impossible under normal circumstances!
It can only be achieved through flexible methods. That is to define another function inside the function.
2. Concept of closure
The f2 function in the above code is the closure.
The definitions of closures in various professional documents are very abstract. My understanding is that closures are functions that can read internal variables of other functions.
In javascript, only child functions inside a function can read local variables, so closures can be simply understood as "functions defined inside a function".
Therefore, in essence, closure is a bridge connecting the inside and outside of a function.
Get local variables:
//10
3. Why do I need closures
Closures can be used in many places. It has two greatest uses,
One is that the variables inside the function can be read as mentioned earlier,
The other is to keep the values of these variables in memory and will not be automatically cleared after f1 call.
Conclusion: local variables cannot be shared and preserved for a long time, while global variables may cause variable pollution. When we hope to have a mechanism that can preserve variables for a long time without causing global pollution.
=========================Closure=============================
//Closure (long-term storage of variables without global pollution)
//It is equivalent to assigning the result of f1 execution to a global variable f
//As a result, f2 is always not recycled in memory. f2 depends on f1, so f1 will not be recycled after calling
========================================================
//Long term preservation
//So that local variables can be saved for a long time
//The result of f1 execution is assigned to a global variable f
//But it doesn't last long
(2) Closure case
Encapsulate the value of the object cache local variable name using the closure principle:
Mode 1:
Mode 2:
Using closures, we can do many things, such as caching local variables to avoid pollution
Conclusion: a closure is a function that references a variable of another function. Because the variable is referenced, it will not be recycled. Therefore, it can be used to encapsulate private variables. This is both an advantage and a disadvantage. Unnecessary closures will only increase memory consumption!
32. Front back separation - data interaction
(1) Data interface specification process
1. Interface documents:
===========================================================================================
//Return type result [{field}, {field}]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button onclick="sendData()">send out</button> <div id="content"></div> <script> function sendData() { // var xmlhttp; // if(window.XMLHttpRequest) { // xmlhttp = new XMLHttpRequest(); // create object // }else { // xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5/IE6 // }; var xmlhttp = new XMLHttpRequest(); //Browser interface xmlhttp.open("get", "http://localhost:3000/get"); //xmlhttp.send(body); // Send get request without parameters //xmlhttp.setRequestHeader("Content-Type","application/json"); // Request header xmlhttp.send() //Send request //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //Receive data (initialization) if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //200 is success console.log(xmlhttp.responseText) //responseText is the information returned by the data //Show the data you get content.innerHTML = xmlhttp.responseText; } } } </script> </body> </html>
(2) http protocol
1. Understanding
Usually, an HTTP client initiates a request to create a TCP connection to the specified port of the server (port 80 by default). The HTTP server listens for client requests on that port. Once the request is received, the server will return a status to the client, such as "HTTP/1.1 200 OK", and the returned content, such as the requested file, error message, or other information.
2. Working principle
The HTTP protocol defines how the Web client requests a Web page from the Web server and how the server transmits the Web page to the client. HTTP protocol adopts request / response model. The client sends a request message to the server, which includes the requested method, URL, protocol version, request header and request data. The server responds with a status line, which includes the protocol version, success or error code, server information, response header and response data.
Request response based pattern
HTTP protocol stipulates that the request is sent from the client, and finally the server responds to the request and returns. In other words, the communication must be established from the client first, and the server will not send a response before receiving the request
Stateless save
HTTP is a stateless protocol that does not save state. The HTTP protocol itself does not save the communication state between request and response. In other words, at the HTTP level, the protocol does not persist the sent request or response.
3.HTTP request method
The HTTP protocol defines eight methods (also known as "actions") to operate the specified resources in different ways:
- GET
Issue a display request to the specified resource. Using the GET method should only be used to read data, and should not be used in operations that produce "side effects", such as in web applications. One reason is that GET may be accessed at will by web spiders and others.
- HEAD
Like the GET method, it sends a request for a specified resource to the server. However, the server will not return this part of the resource. Its advantage is that this method can obtain the "information about the resource" (meta information or metadata) without transmitting all the content.
- POST
Submit data to the specified resource and request the server for processing (such as submitting forms or uploading files). The data is included in the request text. This request may create a new resource, modify an existing resource, or both.
- PUT
Upload its latest content to the specified resource location.
- DELETE
The request server deletes the resource identified by the request URI.
- TRACE
Echo the request received by the server, which is mainly used for testing or diagnosis.
- OPTIONS
This method enables the server to return all HTTP request methods supported by the resource. Use '*' to replace the resource name and send OPTIONS request to the Web server to test whether the server functions normally.
- CONNECT
The HTTP/1.1 protocol is reserved for proxy servers that can change the connection to pipeline. Typically used for links to SSL encrypted servers (via an unencrypted HTTP proxy server).
- The difference between request and get
The data submitted by GET will be placed after the URL, that is, in the request line? Split the URL and transfer data, and connect the parameters with & such as editbook? name=test1&id=123456; The POST method is to put the submitted data into the request body of the HTTP package. Therefore, the data submitted by GET will be displayed in the address bar, while the address bar will not change when submitted by POST
The data size submitted by GET is limited (because the browser limits the length of the URL), while the data submitted by POST method is not limited
4.HTTP status code
The first line of all HTTP responses is the status line, followed by the current HTTP version number, a 3-digit status code, and a phrase describing the status, separated by spaces.
The first number of the status code represents the type of current response:
Common status codes:
200 OK. / / the client request succeeds
400 Bad Request / / there is a syntax error in the client request, which cannot be understood by the server
401 Unauthorized / / the request is not authorized. This status code must be used with the WWW authenticate header field
403 Forbidden / / the server receives the request but refuses to provide the service
404 Not Found / / the requested resource does not exist, eg: an incorrect URL is entered
500 Internal Server Error / / an unexpected error occurs in the server
503 Server Unavailable / / the server cannot process the client's request at present. It may return to normal after a period of time
5. Browser debugging tool
Take chrome as an example
- Arrow button
It is used to select an element on the page to review and view its relevant information. When we click a Dom element under the Elements button page, the arrow button will change to the selection state
- Device Icon
You can switch to different terminals for development mode. When you switch between mobile terminal and pc terminal, you can select different mobile terminal devices and different size ratios
- Elements
This panel displays all the HTML source code after rendering, which is used to view and modify the elements on the page, including DOM tags and css styles, so as to facilitate the debugging of static web pages.
- Console
This panel is used to display the log information in the process of web page loading, including printing, warning, error and other displayable information. At the same time, it is also a js interactive console.
- Sources
The panel is grouped by sites and stores all the requested resources (html,css,jpg,gif,js, etc.). It is precisely because this panel stores all resources, so when debugging js, the object code is found here to facilitate breakpoint debugging
- Network
Network request tab: you can see all resource requests, including network requests, picture resources, html,css, js files and other requests. You can filter request items according to needs. It is generally used for viewing and analyzing network requests, analyzing whether the back-end interface is transmitted correctly, whether the obtained data is accurate, and viewing request headers and request parameters
View the basic information of Network: URL, response status code, response data type, response data size and response time
Specific description of the request document:
- Header: the panel lists the request url, HTTP method, response status code, request header, response header and their respective values, request parameters, and so on
- Preview: preview panel, used to preview resources.
- Response: the response information panel contains content that has not been formatted
- Timing: the details of the resource request take time
- Performance (timeline for older browsers)
The schedule can record and run all the activities of the analysis application. In order to make the interaction of the recording page, open the timeline panel and press the start recording button
- Memory (old version is Profiles):
You can view CPU execution time and memory usage
- Application (formerly Resources)
It will list all resources, as well as HTML5 Database and LocalStore. You can edit and delete the stored content
- Security
Can tell you the security of this website, view valid certificates, etc
- Audits
It can help you analyze the page performance, help to optimize the front-end page, and get the report after analysis
24,HTTP
HTTP protocol, namely Hypertext Transfer Protocol, is the basis of Web networking and one of the commonly used protocols for mobile phone networking. HTTP protocol is an application based on TCP protocol (TCP is the transport layer and HTTP is the application layer).
The interaction process of HTTP is simply the communication between the client and the server, including the request from the client to the server and the response from the server to the client.
Establish a connection between the client and the server. After three handshakes, a stable and reliable connection can be established.
(1) Three handshakes
First handshake: the client sends a syn flag bit to the server; After receiving the syn, the server will return an ack (equivalent to a callback mechanism) and a server-side syn; After receiving the syn sent by the server, the client will send an ack to the server again. Only in this way can the three handshakes be completed.
(2) Four Breakups
It takes three times to establish a connection, but why four times to disconnect
Because tcp is full duplex, it needs to be disconnected separately in each direction, twice in each direction, so 4 times.
(3) Protocol specification
The HTTP protocol is a specification. The format of the request must be limited.
The request format of http protocol is divided into three parts: request line, request header and request body.
1. Request line
Includes three attributes. When describing the corresponding request, the most accurate form is the format of K-V key value pair.
The request header is also a pile of K-V data. Include some additional information in the header information (such as the information format allowed by the client).
2. Request header
Provides information about the request, response, or other sending entity
- Content-Type
text/plain text
application/x-www-form-urlencoded specifies that the content type is a key value pair
Application / octet stream binary stream data
Application / JSON data format
Multipart / form data format
3. Requestor
When sending a request, you can add some user-defined parameters (such as a form) after the request. Send to the background in the form of K=V.
25. Service startup
(1) What is Node?
Node.js is a JavaScript runtime based on Chrome V8 engine
(2) Development framework
- express is a fast, open and minimalist Web development framework.
- koa next generation web development framework
- egg is born for enterprise level framework and application
(3) Start node service
Create package file: npm init Install all dependencies: npm install Installation dependency: cnpm i express perhaps npm install express –save perhaps npm i -S express body-parser Start: node xxx.js stop it: ctrl+c
(4) Message board case:
1. View message information:
Resource URL: http://localhost:3000/data/query |
HTTP protocol: GET |
Data: [{each field}, {each field}] / / the type of data returned
Parameter name | explain | Is it necessary |
name | Name String maximum 255 characters |
|
message | Content String |
|
2. Submit message information:
Resource URL: http://localhost:3000/data/add | ||
HTTP protocol: POST | ||
Parameter name | explain | Is it necessary |
name | The maximum name is 255 characters | must |
message | Type String | must |
<!DOCTYPE> <html lang="zh-en"> <head> <title>js Implement simple message board</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <link href="css/bootstrap.min.css" rel="stylesheet" /> <link href="css/demo.css" rel="stylesheet" /> <script type="text/javascript" src="js/axios.js"></script> <script type="text/javascript" src="js/request.js"></script> <script type="text/javascript" src="js/index3.js"></script> </head> <body> <div class="container"> <div class="form-horizontal"> <div class="form-group"> <label class="col-sm-1 control-label">Nickname?</label> <div class="col-sm-11"> <input type="email" class="form-control name" placeholder="Please enter a nickname"> </div> </div> <div class="form-group"> <label class="col-sm-1 control-label">Leaving a message.</label> <div class="col-sm-11"> <textarea class="form-control message" rows="5" placeholder="Please enter the content"></textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-1 col-sm-11"> <button type="submit" class="btn btn-success submit">Submit a message</button> <button type="submit" class="btn btn-success query">View message</button> </div> </div> </div> <div class="panel panel-primary"> <div class="panel-heading">Message list</div> <div class="panel-body"> <ul class="list-group messageList"> <!-- <li class="list-group-item">Zhang San <span>Said:</span>hello everyone! </li> --> </ul> </div> </div> </div> </body> </html>
Mode 1:
Index.js
window.onload = function () { //Selector package var $ = function (name) { return document.querySelector(name) }; //Submit information $(".submit").onclick = function () { var _name = $(".name").value, _message = $(".message").value; if (!_name || !_message) { alert('Please enter information') } else { var xmlhttp = new XMLHttpRequest(); //Browser interface xmlhttp.open("post", "http://localhost:3000/data/add"); //Sending a get request requires no parameters. name and message correspond to the parameter names in the table xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.send(JSON.stringify({ name: _name, message: _message })); //xmlhttp.send() //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //receive data if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //200 is success console.log(xmlhttp.responseText) } } } }; //Query information $(".query").onclick = function () { } }
Index.js
window.onload = function () { //Selector package var $ = function (name) { return document.querySelector(name) }; //Submit information $(".submit").onclick = function () { var _name = $(".name").value, _message = $(".message").value; if (!_name || !_message) { alert('Please enter information') } else { var xmlhttp = new XMLHttpRequest(); //Browser interface xmlhttp.open("post", "http://localhost:3000/data/add"); xmlhttp.setRequestHeader("Content-Type", "application/json"); //Request header //Sending a get request requires no parameters. name and message correspond to the parameter names in the table xmlhttp.send(JSON.stringify({ name: _name, message: _message })); //xmlhttp.send() //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //receive data if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //200 is success console.log(xmlhttp.responseText) //=======================================Add======================================= //Show the data you get var data = JSON.parse(xmlhttp.responseText); var str = ''; for (var i = 0; i < data.length; i++) { str += '<li class="list-group-item">' + data[i].name + '<span>Said:</span>' + data[i].message + '</li>' } $(".messageList").innerHTML = str; //=================================================================================== } } } }; //Query information $(".query").onclick = function () { } }
//Display
Index.js
window.onload = function () { //Selector package var $ = function (name) { return document.querySelector(name) }; //Submit information $(".submit").onclick = function () { var _name = $(".name").value, _message = $(".message").value; if (!_name || !_message) { alert('Please enter information') } else { var xmlhttp = new XMLHttpRequest(); //Browser interface xmlhttp.open("post", "http://localhost:3000/data/add"); xmlhttp.setRequestHeader("Content-Type", "application/json"); //Request header //Sending a get request requires no parameters. name and message correspond to the parameter names in the table xmlhttp.send(JSON.stringify({ name: _name, message: _message })); //xmlhttp.send() //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //receive data if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //200 is success console.log(xmlhttp.responseText) //=======================================Replace with======================================= list(); //=================================================================================== } } } }; //Query information $(".query").onclick = function () { //=======================================Add======================================= list(); //=================================================================================== } //=======================================Add======================================= function list() { var xmlhttp = new XMLHttpRequest(); //Browser interface xmlhttp.open("get", "http://localhost:3000/data/query"); //xmlhttp.send(body); // Send get request without parameters //xmlhttp.setRequestHeader("Content-Type","application/json"); // Request header xmlhttp.send() //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //receive data if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //Show the data you get var data = JSON.parse(xmlhttp.responseText); var str = ''; for (var i = 0; i < data.length; i++) { str += '<li class="list-group-item">' + data[i].name + '<span>Said:</span>' + data[i].message + '</li>' } $(".messageList").innerHTML = str; } } } //=================================================================================== }
Index.js
window.onload = function () { //Selector package var $ = function (name) { return document.querySelector(name) }; //=======================================Add======================================= var xmlhttp = new XMLHttpRequest(); //Change to global variable //=================================================================================== //Submit information $(".submit").onclick = function () { var _name = $(".name").value, _message = $(".message").value; if (!_name || !_message) { alert('Please enter information') } else { Turn off: //var xmlhttp = new XMLHttpRequest(); // Browser interface xmlhttp.open("post", "http://localhost:3000/data/add"); xmlhttp.setRequestHeader("Content-Type", "application/json"); //Request header //Sending a get request requires no parameters. name and message correspond to the parameter names in the table xmlhttp.send(JSON.stringify({ name: _name, message: _message })); //xmlhttp.send() //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //receive data if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //200 is success console.log(xmlhttp.responseText) list(); } } } }; //Query information $(".query").onclick = function () { list(); } function list() { Turn off: //var xmlhttp = new XMLHttpRequest(); // Browser interface xmlhttp.open("get", "http://localhost:3000/data/query"); //xmlhttp.send(body); // Send get request without parameters //xmlhttp.setRequestHeader("Content-Type","application/json"); // Request header xmlhttp.send() //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //receive data if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //Show the data you get var data = JSON.parse(xmlhttp.responseText); var str = ''; for (var i = 0; i < data.length; i++) { str += '<li class="list-group-item">' + data[i].name + '<span>Said:</span>' + data[i].message + '</li>' } $(".messageList").innerHTML = str; } } } }
Mode 2: axios
Package it:
Index2.js
Copy index js
window.onload = function () { //Selector package var $ = function (name) { return document.querySelector(name) }; var xmlhttp = new XMLHttpRequest(); //Browser interface //Submit information $(".submit").onclick = function () { var _name = $(".name").value, _message = $(".message").value; if (!_name || !_message) { alert('Please enter information') } else { //=======================================Replace with======================================= axios({ method: 'post', url: 'http://localhost:3000/data/add', data: { name: _name, message: _message } }).then(function (res) { list(); }).catch(function () { }) //=================================================================================== } }; //Query information $(".query").onclick = function () { list(); } function list() { //=======================================Replace with======================================= axios({ method: 'get', url: 'http://localhost:3000/data/query' }).then(function (res) { var data = res.data; var str = ''; for (var i = 0; i < data.length; i++) { str += '<li class="list-group-item">' + data[i].name + '<span>Said:</span>' + data[i].message + '</li>' } $(".messageList").innerHTML = str; }).catch(function () { }) //=================================================================================== } }
//Same
Method 3: closure
request.js (request)
function Http() { var xmlhttp = new XMLHttpRequest(); //Browser interface var _url = "http://localhost:3000"; return { //The status after success and the status after error failure request: function (method, url, data, success, error) { //_ url is http://localhost:3000/data/ , the url is query xmlhttp.open(method, _url + url); //Asynchronous open() initialization if (method == 'GET') { xmlhttp.send() } else { xmlhttp.setRequestHeader("Content-Type", "application/json");//Request header xmlhttp.send(data); //Send get request without parameters } //onreadystatechange when the data of the current data source is about to change (when the state changes) xmlhttp.onreadystatechange = function () { //receive data if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { console.log(xmlhttp.responseText) success(xmlhttp.responseText); } else { error() } } } } }
Index3.js
Copy index js
window.onload = function () { //Selector package var $ = function (name) { return document.querySelector(name) }; //=======================================Add======================================= var _http = Http(); //=================================================================================== //Submit information $(".submit").onclick = function () { var _name = $(".name").value, _message = $(".message").value; if (!_name || !_message) { alert('Please enter information') } else { //=======================================Replace with======================================= var data = JSON.stringify({ name: _name, message: _message }); _http.request('POST', '/data/add', data, function (res) { console.log(res); }, function () { } ) //=================================================================================== } }; //Query information $(".query").onclick = function () { list(); } function list() { //=======================================Replace with======================================= _http.request('GET', '/data/query', null, function (res) { console.log(res); //Show the data you get var data = JSON.parse(res); var str = ''; for (var i = 0; i < data.length; i++) { str += '<li class="list-group-item">' + data[i].name + '<span>Said:</span>' + data[i].message + '</li>' } $(".messageList").innerHTML = str; }, function () { }) //=================================================================================== } }
(5) Message board - writing method of the fifth issue
Create package file: npm init Install all dependencies: npm install Installation dependency: cnpm i express perhaps npm install express –save perhaps npm i -S express body-parser Start: node xxx.js stop it: ctrl+c
This is a simple example of a web server:
Serve.js
const express = require('express') //Import express to load dependent packages const app = express() //Create server const port = 3000 //Define a port app.get('/', (req, res) => { //req==request response = = response response res.send('Hello World!') }) app.listen(port, () => { //Monitor 3000 port console.log(`Example app listening at http://localhost:${port}`) })
1. First introduce the express module
2. Use this module to create an HTTP server.
3. The server is set to listen on the specified 3000 port. When the server is ready, the listen callback function will be called
Use.
4. The incoming callback function is executed every time a request is received. Whenever a new request is received, the request event is called and provides two objects: a request object and a response object.
Request provides the details of the request. Through it, you can access the request header and the requested data.
response is used to construct the data to be returned to the client.
1. View message information:
Resource URL: http://localhost:3000/data/query |
HTTP protocol: GET |
Data: [{each field}, {each field}] / / the type of data returned
Parameter name | explain | Is it necessary |
name | Name String maximum 255 characters | no |
message | Content String | must |
2. Submit message information:
Resource URL: http://localhost:3000/data/add | ||
HTTP protocol: POST | ||
Parameter name | explain | Is it necessary |
name | The maximum name is 255 characters | must |
message | Type String | must |
- Query data
Serve.js
const express = require('express') //Import express to load dependent packages const app = express() //Create server const port = 3000 //Define a port app.get('/', (req, res) => { //req==request response = = response response res.send('Hello World!') }) ==================================== add to ========================================== //Add interface //Query interface app.get('/get_list', (req, res) => { //req==request response = = response response var obj = [1,2,3,4,5]; res.send(JSON.stringify(obj)); }) =================================================================================== app.listen(port, () => { //Monitor 3000 port console.log(`Example app listening at http://localhost:${port}`) })
request.js / / closure file
function Http() { var xmlhttp = new XMLHttpRequest(); //XMLHttpRequest is a browser interface var _url = "http://localhost:3000"; return { request: function (method, url, data, success, error) { //method request type, url, interface address, parameter JSON passed in by data, success callback function (success) error (failure) xmlhttp.open(method, _url + url); //Asynchronous open() initialization if (method == 'GET') { xmlhttp.send(); } else { xmlhttp.setRequestHeader("Content-Type", "application/json");//Request header xmlhttp.send(data); //send out }; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { console.log(xmlhttp.responseText) //xmlhttp. Data returned by responseText success(xmlhttp.responseText); } else { error() } } } } }
index.js
window.onload = function () { var choose = function (name) { return document.querySelector(name); }; //Submit data choose(".submit").onclick = function () { } //Query data choose(".query").onclick = function () { showList(); }; //List display function showList() { Http().request('GET', '/get_list', null, function (res) { console.log(res); }, function () { }) } }
Serve.js
const express = require('express') //Import express to load dependent packages const app = express() //Create server const port = 3000 //Define a port ==================================== add to ========================================== //req==request res==response response next var allowCrossDomain = function (req, res, next) { //Customize the middleware and set the response header required by cross domain res.header('Access-Control-Allow-Origin', '*'); //Allow any method //res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); //Allow any type //res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token'); next(); //next step }; //Using cross domain Middleware app.use(allowCrossDomain); //Create application/json parsing without adding this req Body can't get value //app.use(bodyParser.json()) // Create application/x-www-form-urlencoded parsing //app.use(bodyParser.urlencoded({extended: true})) =================================================================================== app.get('/', (req, res) => { //req==request response = = response response res.send('Hello World!') }) ==================================== add to ========================================== //Add interface //Query interface app.get('/get_list', (req, res) => { //req==request response = = response response var obj = [1,2,3,4,5]; res.send(JSON.stringify(arr)); }) =================================================================================== app.listen(port, () => { //Monitor 3000 port console.log(`Example app listening at http://localhost:${port}`) })
//Success
Serve.js
const express = require('express') //Import dependent Package express const app = express() //Create server const port = 3000 //Define a port //req==request res==response response next var allowCrossDomain = function (req, res, next) { //Customize the middleware and set the response header required by cross domain res.header('Access-Control-Allow-Origin', '*'); //Allow any method //res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); //Allow any type //res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token'); next(); //next step }; //Using cross domain Middleware app.use(allowCrossDomain); //Create application/json parsing without adding this req Body can't get value //app.use(bodyParser.json()) // Create application/x-www-form-urlencoded parsing //app.use(bodyParser.urlencoded({extended: true})) app.get('/', (req, res) => { //req==request response = = response response res.send('Hello World!') }) //Add interface
==================================== change into ========================================== //Query interface =================================================================================== app.listen(port, () => { //Monitor 3000 port console.log(`Example app listening at http://localhost:${port}`) })
index.js
window.onload = function () { var choose = function (name) { return document.querySelector(name); }; //Submit data choose(".submit").onclick = function () { } //Query data choose(".query").onclick = function () { showList(); }; //List display function showList() { Http().request('GET', '/get_list', null, function (res) { console.log(res); ==================================== add to ========================================== var data = JSON.parse(res); if (data.code == '200') { var result = data.result; var str = ""; for (var i = 0; i < result.length; i++) { // str+=`<li class="list-group-item">${result[i].name} // <span>Say: < / span > ${result [i]. Message} // </li>` str += '<li class="list-group-item">' + result[i].name + '<span>Said:</span>' + result[i].message + '</li>' }; $(".messageList").innerHTML = str; } =================================================================================== }, function () { }) } }
//Data display
2. Add data
Serve.js
==================================== add to ========================================== var bodyParser = require('body-parser'); //body parsing =================================================================================== const express = require('express') //Import express to load dependent packages const app = express() //Create server const port = 3000 //Define a port //req==request res==response response next var allowCrossDomain = function (req, res, next) { //Customize the middleware and set the response header required by cross domain res.header('Access-Control-Allow-Origin', '*'); //Allow any method res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); //Allow any type res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token'); next(); //next step }; //Using cross domain Middleware app.use(allowCrossDomain); ==================================== add to ========================================== //Create application/json parsing without adding this req Body can't get value app.use(bodyParser.json()) //Create application/x-www-form-urlencoded parsing app.use(bodyParser.urlencoded({extended: true})) =================================================================================== app.get('/', (req, res) => { //req==request response = = response response res.send('Hello World!') }) ==================================== add to ========================================== //Add interface app.post("/add_list", function(req, res){ console.log(req.body); //Get the parameters passed in from the front end res.send(JSON.stringify({code:'200',msg:'success'})); }) =================================================================================== //Query interface app.listen(port, () => { //Monitor 3000 port console.log(`Example app listening at http://localhost:${port}`) })
index.js
window.onload = function () { var choose = function (name) { return document.querySelector(name); }; //Submit data choose(".submit").onclick = function () { ==================================== add to ========================================== //Get value var name = choose(".name").value, message = choose(".message").value; if (!name || !message) { alert("Please enter information!!") } else { var data = JSON.stringify({ name: name, message: message }); Http().request('POST', '/add_list', data, function (res) { console.log(res); showList(); }, function () { }) } =================================================================================== } //Query data choose(".query").onclick = function () { showList(); }; //List display function showList() { Http().request('GET', '/get_list', null, function (res) { console.log(res); var data = JSON.parse(res); if (data.code == '200') { var result = data.result; var str = ""; for (var i = 0; i < result.length; i++) { // str+=`<li class="list-group-item">${result[i].name} // <span>Say: < / span > ${result [i]. Message} // </li>` str += '<li class="list-group-item">' + result[i].name + '<span>Said:</span>' + result[i].message + '</li>' }; choose(".messageList").innerHTML = str; } }, function () { }) } }
//As long as it is submitted, it will be displayed directly below
(6) Cross domain:
//Cross domain required var bodyParser = require('body-parser'); //body parsing var allowCrossDomain = function (req, res, next) { //req==request res==response response next res.header('Access-Control-Allow-Origin', '*');//Customize the middleware and set the response header required by cross domain. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); //Allow any method res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token'); //Allow any type next(); //next step }; //Using cross domain Middleware app.use(allowCrossDomain); //Create application/json parsing without adding this req Body can't get value //app.use(bodyParser.json()) // Create application/x-www-form-urlencoded parsing //app.use(bodyParser.urlencoded({extended: true}))