Realize front-end interaction based on express server
Introduction to express
-
express is a fast, open, and minimal web development framework based on the Node.js platform. It can be used as a server to send data to the front end in the exercise of a small demo and used as a local request address.
-
installation of express
npm install express
-
Introduce express framework
const express = require('express'); //创建应用对象 const app = express();
Introduction to Ajax
- It is possible to perform partial data updates without refreshing the entire browser through asynchronous implementation
- The disadvantage is that there is a cross-domain problem (need to be solved in detail)
Use JSON to implement requests
The previous ajax request used xml as the data transmission in the network, which was later replaced by JSON
-
Transfer data
const data={name:'aixuexi'} let str=JSON.stringify(data); response.send(str)
-
Modify the data on the html page
-
Manually modify the data
let data = JSON.parse(xhr.response) console.log(data); result.innerHTML = data.name;
-
Automatic modification using xhr attributes
xhr.responseType='json'; result.innerHTML = xhr.response.name;//直接可以获取需要的内容
-
Specific instructions for small exercises
-
Use jQuery to get the behavior of the button, and then bind Ajax request access
-
When using Ajax to send a request, define the format url access address, pass parameters, request type, response body result type, and success and failure callback functions
-
Return the background data to the html page, and use native js to implement asynchronous objects
-
Create object
const xhr = new XMLHttpRequest();
-
Bind events to asynchronous objects
xhr.onreadystatechange = function() {}
-
Asynchronous request object
xmlHttp.open(请求方式get|post,“请求服务器端的地址”,true(异步))
-
Send object asynchronously
xmlHttp.send()
-
-
One more point about solving the cross-domain problem of access requests
When the URL requested by the front end and the URL, protocol, domain name, and port number of the backend server are not exactly the same, there is a problem that it cannot be accessed
- jsonp method, implemented by code on the server side
- CORS tells the browser that the access needs to be cross-domain by setting the HTTP response header