NodeJS framework Express

Express

The summary content comes from a PPT for studying at home this winter vacation

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 various web applications. We can use the npm install express command to download.

1.2 Express framework features

  • Provides a convenient and concise route definition method
  • Simplified processing for obtaining HTTP request parameters
  • High degree of support for template engine, easy to render dynamic HTML pages
  • Provides a middleware mechanism to effectively control HTTP requests
  • Have a large number of third-party middleware to extend the function

1.3 Comparison of routing between native Node.js and Express framework

 app.on('request', (req, res) => {
    
    
     // 获取客户端的请求路径
     let {
    
     pathname } = url.parse(req.url);
     // 对请求路径进行判断 不同的路径地址响应不同的内容
     if (pathname == '/' || pathname == 'index') {
    
    
        res.end('欢迎来到首页');
     } else if (pathname == '/list') {
    
    
        res.end('欢迎来到列表页页');
     } else if (pathname == '/about') {
    
    
        res.end('欢迎来到关于我们页面')
     } else {
    
    
        res.end('抱歉, 您访问的页面出游了');
     }
 });
 // 当客户端以get方式访问/时
 app.get('/', (req, res) => {
    
    
     // 对客户端做出响应
     res.send('Hello Express');
 });

 // 当客户端以post方式访问/add路由时
 app.post('/add', (req, res) => {
    
    
    res.send('使用post方式请求了/add路由');
 });

1.4 Comparison of native Node.js and Express frameworks to obtain request parameters

 app.on('request', (req, res) => {
    
    
    // 获取GET参数
    let {
    
    query} = url.parse(req.url, true);
    // 获取POST参数
    let postData = '';
    req.on('data', (chunk) => {
    
    
        postData += chunk;
    });
    req.on('end', () => {
    
    
        console.log(querystring.parse(postData)
    })); 
 });
 app.get('/', (req, res) => {
    
    
    // 获取GET参数
    console.log(req.query);
 });

 app.post('/', (req, res) => {
    
    
    // 获取POST参数
    console.log(req.body);
 }) 

1.5 Express first experience

Using the Express framework to create a web server is very simple, just call the function returned by the express module.

 // 引入Express框架
 const express = require('express');
 // 使用框架创建web服务器
 const app = express();
 // 当客户端以get方式访问/路由时
 app.get('/', (req, res) => {
    
    
    // 对客户端做出响应 send方法会根据内容的类型自动设置请求头
    res.send('Hello Express'); // <h2>Hello Express</h2> {say: 'hello'}
 });
 // 程序监听3000端口
 app.listen(3000);

2. Middleware

2.1 What is middleware

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

Middleware is mainly composed of two parts, middleware method and request processing function.
The middleware method is provided by Express, which is responsible for intercepting the request, and the request processing function is provided by the developer, which is responsible for processing the request.

 app.get('请求路径', '处理函数')   // 接收并处理get请求
 app.post('请求路径', '处理函数')  // 接收并处理post请求

You can set up multiple middleware for the same request, and process the same request multiple times.
By default, requests are matched against the middleware in order from top to bottom. Once the matching is successful, the matching is terminated.
The next method can be called to transfer the 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 = "张三";
     next();
 });
 app.get('/request', (req, res) => {
    
    
     res.send(req.name);
 });

2.2 app.use middleware usage

app.use matches all request methods and can be directly passed in the request processing function, which means that all requests are received.

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

The first parameter of app.use can also be passed into the request address, which means that no matter what the request method is, the request will be received as long as it is the request address.

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

2.3 Middleware application

  • Route protection, when the client accesses the page that needs to be logged in, it can first use the middleware to determine the user's login status. If the user is not logged in, it will intercept the request and respond directly to prohibit the user from entering the page that needs to be logged in.
  • The website maintenance announcement defines the middleware that receives all requests at the top of all routes and responds directly to the client. The website is under maintenance.
  • Custom 404 page

2.4 Error handling middleware

In the process of program execution, some unexpected errors will inevitably occur, such as file reading failure and database connection failure.
Error handling middleware is a place where errors are handled centrally.

 app.use((err, req, res, next) => {
    
    
     res.status(500).send('服务器发生未知错误');
 })

When an error occurs in the program, call the next() method and pass the error information to the next() method in the form of parameters to trigger the error handling middleware.

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

2.5 Catching errors

In node.js, the error information of the asynchronous API is obtained through the callback function, and the asynchronous API that supports the Promise object can be caught by the catch method.
If an error occurs in asynchronous function execution, how to catch the error?
Try catch can catch errors that occur during the execution of asynchronous functions and other synchronous codes, but not errors that occur with other types of APIs.

 app.get("/", async (req, res, next) => {
    
    
     try {
    
    
         await User.find({
    
    name: '张三'})
     }catch(ex) {
    
    
         next(ex);
     }
 });

3. Express request processing

3.1 Building modular routing

 const express = require('express') 
 // 创建路由对象
 const home = express.Router();
 // 将路由和请求路径进行匹配
 app.use('/home', home);
  // 在home路由下继续创建路由
 home.get('/index', () => {
    
    
          //  /home/index
         res.send('欢迎来到博客展示页面');
 });

or:

 // home.js
 const home = express.Router(); 
 home.get('/index', () => {
    
    
     res.send('欢迎来到博客展示页面');
 });
 module.exports = home;
 // admin.js
 const admin = express.Router();
 admin.get('/index', () => {
    
    
     res.send('欢迎来到博客管理页面');
 });
 module.exports = admin;
 // app.js
 const home = require('./route/home.js');
 const admin = require('./route/admin.js');
 app.use('/home', home);
 app.use('/admin', admin);

3.3 Obtaining GET parameters

In the Express framework, you can use req.query to get the GET parameters, and the framework will convert the GET parameters into objects and return them.

 // 接收地址栏中问号后面的参数
 // 例如: http://localhost:3000/?name=zhangsan&age=30
 app.get('/', (req, res) => {
    
    
    console.log(req.query); // {"name": "zhangsan", "age": "30"}
 });

3.4 Obtaining POST parameters

To receive post request parameters in Express, the third-party package body-parser is needed.

 // 引入body-parser模块
 const bodyParser = require('body-parser');
 // 配置body-parser模块
 app.use(bodyParser.urlencoded({
    
     extended: false }));
 // 接收请求
 app.post('/add', (req, res) => {
    
    
    // 接收请求参数
    console.log(req.body);
 }) 

3.5 Express routing parameters

 app.get('/find/:id', (req, res) => {
    
     
     console.log(req.params); // {id: 123} 
 });

localhost:3000/find/123

3.6 Processing of static resources

Static files, such as img, CSS, JavaScript files, etc., can be conveniently hosted by express.static built into Express.

 app.use(express.static('public'));

Now, the files under the public directory can be accessed.

  • 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

In order to enable the art-template template engine to better cooperate with the Express framework, the template engine officially encapsulates express-art-template on the basis of the original art-template template engine.
Use the npm install art-template express-art-template command to install.

  // 当渲染后缀为art的模板时 使用express-art-template
 app.engine('art', require('express-art-template'));
  // 设置模板存放目录
 app.set('views', path.join(__dirname, 'views'));
  // 渲染模板时不写后缀 默认拼接art后缀
 app.set('view engine', 'art');
 app.get('/', (req, res) => {
    
    
     // 渲染模板
     res.render('index');
 }); 

4.2 app.locals object

Set the variable under the app.locals object, this data can be obtained in all templates.

 app.locals.users = [{
    
    
     name: '张三',
     age: 20
 },{
    
    
     name: '李四',
     age: 20
}]

Guess you like

Origin blog.csdn.net/jal517486222/article/details/109628698