Express

1. Introduction of Express

Express is a minimalist, flexible Web application development framework based on the Node.js platform. It provides a series of powerful features to help you quickly create a variety of Web and mobile applications.

Express is simply a module that runs in a Node to build a server.

2. Use Express

/ / 1. Install the express
npm i express 
//2. Import express package
const express = require("express");
//3. Create application objects
const app = express();
//4. Route Settings
app.get("/".(request, response) = > {
  // Set the response
  response.end("Hello Express");
});
//5. Listen to the port to start the service
app.listen(80.() = > {
  console.log("Service has started.. Port 80 listening....");
});
Copy the code

3. Express routing

1. What is the Route

Routing refers to how to define application endpoints (URIs) and how to respond to client requests.

A route consists of a URI, HTTP request (GET, POST, etc.), and several handles.

2. The definition of the Route

We can define a route as three parts:

Part 1: Methods for HTTP Requests (GET or POST)

Part two: URI paths

Part three: callback functions

3. Implementation of Route

Express provides a series of functions that make it easy to implement routing:

App. (path, the callback)

Method refers to HTTP request methods, such as app.get(), app.post()

Path refers to the URL address to be processed through the callback function

The callback argument is the request handler that should process the request and send the response back to the client

const express = require("express");
const fs = require("fs");
const app = express();

// Create a routing rule
app.get("/".(request, response) = > {
    // The send method is the express encapsulated response method
    response.send("Routing page");
});

app.get("/admin".(request, response) = > {
    response.send("Background Page");
});
// The login page is displayed
app.get("/login".(request, response) = > {
    const body = fs.readFileSync("./form.html");
    response.end(body);
});

app.get("/register".(request, response) = > {
    response.send("Registration Page");
});

app.post("/login".(request, response) = > {
    response.send("Login Processing");
});

app.listen(80);
Copy the code
<! -- form.html -->
<form action="/login" method="post">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit" value="Login" >
</form>
Copy the code

4. Running process of Route

When the Express server receives an HTTP request, it looks for routes that have been defined for the appropriate HTTP methods and paths

If one is found, Request and Response objects are created and passed to the route’s callback function

We can read the Request from the Request object and return the Response from the Response object

Express also provides the All () method to handle both requests.

// The all method responds to both GET and POST
app.all("/test".(request, response) = > {
    response.send("Test");
});
Copy the code

4. The Request object

1. What is the Request object

The Request object is the first parameter in the route callback function and represents the Request information sent by the user to the server

The Request object can read the parameters in the query string of the URL address and the parameters in the Request body of the POST Request.

2. Properties and methods of the Request object

Properties/methods describe
request.query Gets an object as an argument to the query string of the GET request
request.params Get the parameters of the route, and get an object
request.body Get the body of the POST request and get an object (with middleware)
request.get(xxxx) Gets the value corresponding to the specified key in the request header

Use 3.

// Import the Express package
const express = require("express");
// Create an application object
const app = express();

// Route Settings
app.get("/".(request, response) = > {
  // Set the response
  response.end("Hello Express");
});

app.get("/req".(request, response) = > {
    // Get the request method
    console.log(request.method);
    // Get the requested URL
    console.log(request.url);
    // Get the HTTP version of the request
    console.log(request.httpVersion);
    // Get the request header information
    console.log(request.headers);
    // Get the query string argument
    console.log(request.query);
    // Get the specified request header information
    console.log(request.get("host"));
    response.send("Access to requested content");
});

//1. Fill in the placeholder (: identifier) in the URL rule
app.get("/news/:id.html".(request, response) = > {
  //2. Obtain path parameters in the URL
  let id = request.params.id;
  console.log(id);
  response.send(` id for${id}The news of `);
});

// Copy the route Settings of jingdong
app.get("/:abc.html".(request, response) = > {
  let id = request.params.abc;
  response.send(` id for${id}Product information ');
});

// Listen on the port to start the service
app.listen(80.() = > {
  console.log("Service has started.. Port 80 listening....");
});
Copy the code

4. Modify the hosts file

The path

C:\Windows\System32\drivers\etc\hosts
Copy the code

Open the file and edit it

127.0.0.1       item.jd.com
127.0.0.1       qq.com
Copy the code

And then save the file

5. The Response object

1. What is the Response object

The Response object is the second parameter in the route callback function and represents the Response information sent by the server to the user.

Through the Response object, you can set the contents of the Response message, including the Response header and the Response body.

2. Properties and methods of the Response object

Properties/methods describe
response.send() Make a response to the browser
response.end() Make a response to the browser (no automatic appending of the response header)
response.download() Tell the browser to download a file
response.sendFile() Send a file to the browser
response.redirect() Redirect to a new address (URL)
response.set(header,value) Customize the response header content
response.get() Gets the value corresponding to the key specified in the response header
res.status(code) Set the response status code

Use 3.

// Import the Express package
const express = require("express");
// Create an application object
const app = express();
// Route Settings
app.get("/res".(request, response) = > {
    // Response status code
    // response.statusCode = 200;
    response.status(500);
    // Response status string
    response.statusMessage = "ok";
    / / response headers
    // response.setHeader('week','san');
    // response.setHeader('Content-type','text/html; charset=utf-8');
    response.set("a"."100");
    / / response body
    // response.write('Hello');
    After the response body is set, the response header cannot be set
    response.send("The day the broken sword is rebuilt, the knight returns.");
    // Download the response
    response.download("./package.json");
    // Respond the contents of a file to the browser (must be an absolute path)
    response.sendFile(__dirname + "/form.html");
    / / jump
    response.redirect("https://www.baidu.com");
});
// Listen on the port to start the service
app.listen(80.() = > {
    console.log("Service has started.. Port 80 listening....");
});
Copy the code

4. Website root directory

The site root directory will be placed

  • The HTML file
  • The CSS file
  • JS file
  • The picture
  • video
  • audio
  • The font

For resources whose content changes frequently, set routing rules to respond to web content

// Configure the root directory of the web site
app.use(express.static(__dirname + "/public"));
Copy the code

6. The middleware

1. Introduction to middleware

Express is a web development framework that is minimalist in its own right, entirely composed of routing and middleware: essentially, an Express application calls various middleware.

Middleware is a function that accesses request objects, response objects, and Middleware in the request-response cycle of a Web application, usually named next.

2. Middleware

  1. Execute any code.
  2. Modify the request and response objects.
  3. Terminates the request-response loop.
  4. Call the next middleware in the stack.

3. Classification of middleware

  1. Application-level middleware (filtering illegal requests, such as anti-theft)
  2. Third party middleware (middleware downloaded via NPM, such as Body-Parser)
  3. Built-in middleware (middleware packaged inside Express)
  4. Router Middleware

4. Use of middleware

Time processing plug-in

momentjs.cn/

Global middleware

// Middleware is a function
const express = require('express');
const moment = require('moment');
const fs = require('fs');

const app = express();

//1. Declare a middleware function next as a value of function type, console.log(' record ');
let record = function(request, response, next){
    Date getFulleYear getMonth getDate
    let time = moment().format('YYYY-MM-DD HH:mm:ss');
    // Get the path
    const path = request.url;
    // Concatenates the string to be written
    let str = ` [${time}]  ${path}\r\n`;
    // Write to the file
    fs.writeFileSync('./access.log', str, {flag: 'a'});
    // Call next
    next();
}


Middleware configuration (global middleware)
app.use(record)

/ / routing
Access.log [2020-10-26 10:10:10] /
app.get('/'.(request, response) = > {
    response.send('Middleware');
});

app.get('/admin', checkUser, (request, response) = > {
    response.send('Background home page')}); app.get('/setting', checkUser, (request, response) = > {
    response.send('Background Settings');
});

app.get('/shuju', checkUser, (request, response) = > {
    response.send('Background data page');
});

app.get('/home'.(request, response) = > {
    response.send('Front page');
})

app.get('/cart'.(request, response) = > {
    response.send('Shopping cart');
});

app.get('/login'.(request, response) = > {
    response.send('Login page');
});

app.listen(80);
Copy the code

Routing middleware

127.0.0.1/admin? admin=1
let checkUser = function(request, response, next){
    // Get the admin URL parameter
    let isAdmin = request.query.admin;
    / / determine
    if(isAdmin === '1') {// The condition is met
        next();
    }else{
        // Go to the login page
        response.redirect('/login'); }}// add the function to the second argument
app.get('/admin', checkUser, (request, response) = > {
    response.send('Background home page')}); app.get('/setting', checkUser, (request, response) = > {
    response.send('Background Settings');
});
app.get('/home'.(request, response) = > {
    response.send('Front page');
})
app.get('/cart'.(request, response) = > {
    response.send('Shopping cart');
});
Copy the code

Other Middleware

// Import the Express package
const express = require("express");
// Create an application object
const app = express();
/ / 1 > is introduced into the body - the parser
var bodyParser = require("body-parser");
//2> parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// Simple custom request body processing middleware
let myBodyParser = function (request, response, next) {
  // Get the request body
  let body = ""; Bind data event Request. on("data".(chunk) = > {
    body += chunk.toString();
  });

  request.on("end".() = > {
    / / parsing
    const data = qs.parse(body);
    // Store the request body object as a property in the Request object
    request.body = data;
    next();
  });
};

Static resource service middleware
app.use(express.static("./public"));

//2. Middleware body-parser for body parameters
app.get("/form".(request, response) = > {
  // Respond to the contents of a file
  response.sendFile(__dirname + "/form.html");
});

app.post("/login".(request, response) = > {
  // Get the request body-parser
  //3> request.body Gets an attribute in the request body
  console.log(request.body.username);
  console.log(request.body.password);
  response.send("Request body accepted");
});

// Listen on the port to start the service
app.listen(80.() = > {
  console.log("Service has started.. Port 80 listening....");
});
Copy the code

7. The Router Router

1. What is the Router

A Router is a complete middleware and routing system, which can also be considered a small APP object.

2. Why use Router

To better categorize and manage routes

3. The use of the Router

/ / install express
// Import the Express package
const express = require("express");
// Create an application object
const app = express();
/ / into the router
const router = require("./routes/router");
const adminRouter = require("./routes/admin");

//1. Create a routes folder
//2. Create a separate router.js file
//3. Modify the code in router.js (4 steps)
//4. Import router.js into the main file
//5. app.use Sets middleware
app.use(router);
app.use(adminRouter);

// Listen on the port to start the service
app.listen(80.() = > {
  console.log("Service has started.. Port 80 listening....");
});
Copy the code
// router.js
//1. Import express package
const express = require('express');
Router is a miniature app object
const router = express.Router();
//3. Routing rules
router.get('/admin'.(request, response) = > {
    response.send('

'
)}); router.get('/logout'.(request, response) = > { response.send('

Log out

'
)});/ / 4. Exposure module.exports = router; Copy the code