Express framework: Express middleware app Use of use()

Time:2022-6-20

1. Express framework

The express framework is a kind of node framework.

Installing the express framework

npm install express --save

Simple use of Express

After installing the express framework, you will see node in the project directory_ Modules depends on the file package. Create a new routes directory under the project directory and an index JS file is used to export the routing data requested in different ways.

  • Index JS file
    The general data format is JSON
exports.getHome = (req,res) => {
    Res.send ('Get the homepage data ')
}

exports.getStudent = (req,res) => {
    Res.send ('student data obtained by get ')
}

exports.postHome = (req,res) => {
    Res.send ('post obtained homepage data ')
}

exports.postStudent = (req,res) => {
    Res.send ('student data obtained by post ')
}

Then create a new demo in the project directory JS file to use express and obtain the data content in routes through the express framework.

  • demo. JS file
//Introducing Express
const express = require('express');

// console.log(express);

//Create application
const app = express();

//Use() use
// app.use(function(req,res){
//     res.send({
//         name:'xiaochen',
//         age:20
//     })
// })

//Import the routing file for the page
const routes = require('./routes/index');

//Data obtained by get when accessing the root directory of the homepage
app.get('/', routes.getHome);
app.get('/student', routes.getStudent);

//Data obtained by post when accessing the student directory
app.post('/', routes.postHome);
app.post('/student', routes.postStudent);

//Listening port
app.listen(3000, () => {
    console.log('server start at 3000 port....');
})
Express framework: Express middleware app Use of use()

Partial results png

You can see that the content of data can be requested through post, which is a simple way to use express.

2. Middleware

2.1 functions of Middleware

The middleware can execute any code, modify the request and response objects, or terminate the request response cycle.

  • Application scenario: available for website maintenance announcements
2.2 use of middleware app use()

app. The use() middleware has two parameters,

  • One is the path path, which means that the middleware can be executed only after the corresponding path is specified.
  • The other is a callback function, which is used to process the logic part of the current middleware

app. The second parameter callback function of use () has three parameters. The first parameter is request, the requested data, the second is response, the data returned from the response, and the third parameter tail function next. If the middleware does not call the next function, the entire request response process will be interrupted and will not be executed later.

  • Create a JS file for the middleware
    The following part of the code simply simulates some logic of the website maintenance announcement through the use of the middleware. In the first middleware, the time function of date() is used to obtain the current time point, and then judge whether the time exceeds the time point in the evening. If it exceeds the time point, the data acquisition request is terminated. The website maintenance interface is displayed. If it does not exceed the time point, the next middleware app is accessed through the tail function of the middleware next() Use() to get the data of the interface response to the front end.
//Introducing the express framework
const express = require('express');

//Create program
const app = express();

//Create a middleware app use()
app.use(function (request, response, next) {
    let date = new Date();
    let hours = date.getHours();
    let minute = date.getMinutes();
    let seconds = date.getSeconds();
    // response.send(hours + ':' + minute + ':' + seconds)
    //Judge whether the current time has passed 10:00 p.m
    if (hours >= 22) {
        //After 10 p.m., stop here
        response. Send ('<h1> website maintenance... </h1>')
    } else {
        //If it doesn't exceed 10:00 p.m., then use the tail function of the middleware to obtain the data of the website
        next();
    }
})

//The above code will not execute the middleware until next ()
app.use(function (request, response, next) {
    response.send({
        Name: 'Xiao Chen',
        addr: 'china',
        data: {
            height: 1,
            weight: 1
        }
    });
})

app.listen(3000, () => {
    console.log('Server start at 3000 port.....')
})
Express framework: Express middleware app Use of use()

If 11 o’clock exceeds 10 o’clock, the website maintenance will be displayed png
  • If it is judged that the modification is less than 10 points, let the middleware obtain the data content of the next middleware through the tail function
//Introducing the express framework
const express = require('express');

//Create program
const app = express();

//Create a middleware app use()
app.use(function (request, response, next) {
    let date = new Date();
    let hours = date.getHours();
    let minute = date.getMinutes();
    let seconds = date.getSeconds();
    // response.send(hours + ':' + minute + ':' + seconds)
    if (hours < 22) {
        response. Send ('<h1> website maintenance... </h1>')
    } else {
        next();
    }
})

//The above code will not execute the middleware until next ()
app.use(function (request, response, next) {
    response.send({
        Name: 'Xiao Chen',
        addr: 'china',
        data: {
            height: 1,
            weight: 1
        }
    });
})

app.listen(3000, () => {
    console.log('Server start at 3000 port.....')
})
Express framework: Express middleware app Use of use()

Enter the next middleware through the tail function png
2.3 classification of Middleware

Middleware can be divided into middleware with path and middleware without path according to parameters.
Middleware with path:

//Middleware with path
app.use('/student',(req,res,next)=>{
    Res.send ('currently student page... ')
})

Express framework: Express middleware app Use of use()

Only the address bar has student png

Middleware without path:

//Middleware without path
app.use((req,res,next)=>{
    Res.send ('middleware without path can be accessed... ');
    next()
})
Express framework: Express middleware app Use of use()

Can be accessed by any png
2.4 middleware with multiple callback functions

In the second parameter of the middleware, it is not limited to having only one callback function. It can have multiple callback functions.
Specific wording:

//Middleware with multiple callback functions
app.use('/demo', (req, res, next) => {
    console. Log ('before the first tail function..... ');
    next();
    console. Log ('after the first tail function..... ');
}, (req, res, next) => {
    console. Log ('before the second tail function..... ');
    next();
    console. Log ('after the second tail function..... ');
}, (req, res, next) => {
    console. Log ('before the third tail function..... ');
    next();
    console. Log ('after the third tail function..... ');
})
Express framework: Express middleware app Use of use()

PowerShell prints the results png

The execution mode of middleware is called onion mode on the official website and in many places

Express framework: Express middleware app Use of use()

notes. png

Recommended Today

20220506 Getting Started

preface Document address 1. introduction to spring boot Spring boot helps you create standalone, production level spring based applications that can run. You can use spring boot to createjava -jarOr a more traditional War deployment launched Java application. We also provide a runspring scriptsCommand line tools for. The main objectives of spring boot are: Provide […]