Express framework

  • directory

  • Express framework introduction and initial experience

  • Express middleware

  • Express framework request processing

  • Epress-art-template Template engine

The official documentation


1. Introduction and initial experience of Express framework

1.1 What is the Express framework

Express is a Web application development framework based on the Node platform. It provides a series of powerful features to help you create a variety of Web applications. We can download it using the NPM install Express command.

1.2 Express Framework Features

  1. Provides a convenient and concise route definition method

  2. Getting HTTP request parameters is simplified

  3. High support for template engine, easy to render dynamic HTML pages

  4. Provides middleware mechanisms to effectively control HTTP requests

  5. There is a lot of third-party middleware to extend the functionality

1.3Native Node.js vs. Express routing

The original Node. Js:

app.on('request'.(req, res) = > {
     // Get the client request path
 const pathname = new URL(req.url, "http://localhost:3000").pathname;
     // Determine the request path. Different paths respond to different content
     if (pathname == '/' || pathname == 'index') {
        res.end('Welcome to the home page');
     } else if (pathname == '/list') {
        res.end('Welcome to the list page');
     } else if (pathname == '/about') {
        res.end('Welcome to the About us page')}else {
        res.end('Sorry, the page you visited is gone.'); }});Copy the code

Express framework:

 // When the client accesses/in get mode
 app.get('/'.(req, res) = > {
     // Respond to the client
     res.send('Hello Express');
 });

 // When the client accesses the /add route in POST mode
 app.post('/add'.(req, res) = > {
    res.send('Post requested /add route');
 });

Copy the code

1.4Get request parameters by comparing native Node.js with Express framework

The original Node. Js:

app.on('request'.(req, res) = > {
    // GET the GET argument
  const query = new URL(req.url, "http://localhost:3000").searchParams;
    // Get the POST argument
    let postData = ' ';
    req.on('data'.(chunk) = > {
        postData += chunk;
    });
    req.on('end'.() = > {
        console.log(querystring.parse(postData)
    })); 
 });

Copy the code

Express framework:

 app.get('/'.(req, res) = > {
    // GET the GET argument
    console.log(req.query);
 });

 app.post('/'.(req, res) = > {
    // Get the POST argument
    console.log(req.body);
 }) 

Copy the code

1.5 At the beginning of Express experience

 // Introduce the Express framework
 const express = require('express');
 // Create a Web server using the framework
 const app = express();
 // When the client accesses/routes in get mode
 app.get('/'.(req, res) = > {
    The send method automatically sets the request header based on the type of content
    res.send('Hello Express'); // <h2>Hello Express</h2> {say: 'hello'}
 });
 // The program listens on port 3000
 app.listen(3000);

Copy the code

2. The middleware

2.1 What is middleware

Middleware is a collection of methods that can receive requests from clients, respond to requests, or pass requests on to the next middleware.

Middleware mainly consists of two parts, middleware methods and request processing functions.

Middleware methods are provided by Express to intercept requests, and request handlers are provided by developers to process requests.

 app.get('Request path'.'Handler function')   // Receive and process get requests
 app.post('Request path'.'Handler function')  // Receive and process post requests
Copy the code

You can set up multiple middleware for the same request to process the same request multiple times.

By default, requests are matched to the middleware from top to bottom, and once a match is successful, the match is terminated.

The next method can be called to give control of the request to the next middleware until the middleware that ends the request is encountered.

app.get('/request'.(req, res, next) = > {
     req.name = "Zhang";
     next();
 });
 app.get('/request'.(req, res) = > {
     res.send(req.name);
 });
Copy the code

2.2 app.useMiddleware usage

App.use matches all request modes and can be passed directly to the request handler to receive all requests.

 app.use((req, res, next) = > {
     console.log(req.url);
     next();
 });

Copy the code

App.use the first parameter can also be passed to the request address, indicating that the request will be received at the request address regardless of the type of request.

 app.use('/admin'.(req, res, next) = > {
     console.log(req.url);
     next();
 });

Copy the code

2.3 Middleware application

1. Route protection: When accessing the page to be logged in, the client can use the middleware to determine the user’s login status. If the user does not log in, the client intercepts the request and responds directly to prevent the user from accessing the page to be logged in.

1. Route protection
app.use((req, res, next) = > {
     let isLogined = true;
     if (isLogined) {
        next();
    } else {
         res.send('User not logged in, please log in')
     }
 })
 app.get('/index'.(req, res) = > {
     res.send('User logged in, welcome to the main page');
 })
Copy the code

2. Website maintenance notice, at the top of all routes to define the middleware to receive all requests, directly respond to the client, the website is under maintenance.

// 2. Website announcement
app.use((req, res) = > {
    res.send('The site is under maintenance... ')})Copy the code

3. Customize the 404 page

3.404 Error page (placed at the end of all routes)
app.use((req, res) = > {
    res.status(404).send('Error, page found')// Allow chained programming
})
Copy the code

2.4 Error handling middleware

In the process of program execution, it is inevitable that there will be some unexpected errors, such as file reading failure, database connection failure.

Error handling middleware is a centralized place to handle errors.

 app.use((err, req, res, next) = > {
     res.status(500).send('Unknown server error');
 })

Copy the code

When the program encounters an error, the next() method is called and the error message is passed to the next() method as an argument to trigger the error-handling middleware.

app.get("/".(req, res, next) = > {
     fs.readFile("/file-does-not-exist".(err, data) = > {
         if(err) { next(err); }}); });Copy the code

2.5 Capture the error

In Node.js, the error information of the asynchronous API is obtained through the callback function, and the error of the asynchronous API that supports the Promise object can be caught through the catch method.

How do you catch errors in asynchronous function execution?

const fs = require('fs');
const promisify = require('util').promisify
const readFile = promisify(fs.readFile);
app.get('/'.async (req, res, next) => {
    try {
        let result = await readFile('01.js'.'utf8')
        res.send(result);
    } catch(error) { next(error); }})// Error handling middleware
app.use((err, req, res, next) = > {
    res.status(500).send(err.message);
})
Copy the code

3.Express framework request processing

3.1Building modular routing

//app.js
const express = require('express') 
 // Create a routing object
 const home = express.Router();
 // Match the route with the request path
 app.use('/home', home);
  // Continue to create a route under the home route
 home.get('/index'.() = > {
          // /home/index
         res.send('Welcome to the blog presentation page');
 });
Copy the code

The above code is extracted and separated by modules

// home.js
 const home = express.Router(); 
 home.get('/index'.() = > {
     res.send('Welcome to the blog presentation page');
 });
 module.exports = home;

Copy the code
// admin.js
 const admin = express.Router();
 admin.get('/index'.() = > {
     res.send('Welcome to the Blog Management page');
 });
 module.exports = admin;

Copy the code
 // app.js
 const home = require('./route/home.js');
 const admin = require('./route/admin.js');
 app.use('/home', home);
 app.use('/admin', admin);

Copy the code

If you want to access the result of the home.js request, you need to add the /home path admin.js

3.2 Obtaining the GET Parameter

The Express framework uses req.query to GET the GET argument, which is internally converted to an object and returned.

 // Accept the argument after the question mark in the address bar
 // For example: http://localhost:3000/? name=zhangsan&age=30
 app.get('/'.(req, res) = > {
    console.log(req.query); // {"name": "zhangsan", "age": "30"}
 });

Copy the code

3.3 Obtaining POST Parameters

The Express framework uses req.body to get the POST argument, but to default mainly to underdefine, middleware must be configured without importing third-party modules that are now embedded in the Express framework

// Use middleware to view official documentation
app.use(express.json())
// extended: The format in which the request parameters are handled internally by the third-party module QS
app.use(express.urlencoded({ extended: true }))
// Get the POST argument
app.post('/index'.(req, res) = > {
    console.log(req.body);
    res.send(req.body);
})
Copy the code

3.4Express Route Parameters

In the Express framework, req.params can be used to obtain the object type of the corresponding route parameter

app.get('/find/:id'.(req, res) = > { 
     console.log(req.params); // {id: 123} 
 });
localhost:3000/find/123 // The value entered in the address bar

Copy the code

3.5 Processing Static Resources

Static (param) method in the Express framework The param parameter is the directory storing static resources. The param parameter needs to be combined with path.join. Static files, such as IMG, CSS, and JavaScript files, can be conveniently hosted.

 app.use(express.static(path.join(__dirname,'public'));
Copy the code

The files under the public directory are now accessible.

  • http://localhost:3000/images/kitten.jpg
  • http://localhost:3000/css/style.css
  • http://localhost:3000/js/app.js
  • http://localhost:3000/images/bg.png
  • http://localhost:3000/hello.html

4. Express-art-template Template engine

4.1 Template Engine Configuration

  • In order to make the Art-template template engine can better cooperate with the Express framework, the template engine officially packaged express-Art-Template on the basis of the original Art-template template engine.
  • Run the NPM install art-template express-art-template command to install.
// Tell the Express framework what template suffix and what template engine to use
app.engine('art'.require('express-art-template'));
// Tell express framework template files where to store them
app.set('views', path.join(__dirname, 'views'));
// Tells the express framework template file the default suffix
app.set('view engine'.'art');
Copy the code

Once configured, use the res.render() method

app.get('/index'.(req, res) = > {
    res.render('list', {
        msg: 123
    });// No need to add file suffix
})
Copy the code

4.2 app. Locals object

Set variables to the app.locals object, which is available in all templates.

 app.locals.users = [{
     name: 'Joe'.age: 20}, {name: 'bill'.age: 20
}]
Copy the code