This is the 9th day of my participation in Gwen Challenge

Lynne, a front-end development engineer who can cry, love and laugh forever. In the Internet wave, love life and technology.

preface

Sure enough, learning with a purpose is more efficient. Every time I learn nodeJS, I forget it after reading it.

Today, let’s talk about the learning experience of Node middleware!

Node Middleware Concept

What is middleware?

Literally, handlers placed between one layer of software and another.

Node middleware is a function that is executed during the lifecycle of a request to the Node server.

Each middleware has access to HTTP requests and responses for all routes to which it is attached.

In addition, the middleware can terminate the HTTP request or pass it to another middleware function using Next. This “chain” of middleware allows you to partition code and create reusable middleware.

To put it simply: middleware is the processing logic from the beginning of the HTTP request to the end of the response, and usually needs to process the request and response.

Why use middleware?

So what problem does middleware solve?

Suppose you’re running a Web application using Node.js on a Web server, and you need to log in to some pages of the application.

When the Web server receives a data request, Node provides you with a request object that contains information about the user and the requested data. Node also gives you access to response objects, which you can modify before the Web server responds to the user. These objects are usually shortened to REq, RES.

Middleware functions are ideal places to modify REQ and RES objects with relevant information. For example, after a user logs in, you can retrieve their user details from the database and store those details in res.user.

A simple middleware

This paper introduces the basic structure of middleware through a simple middleware.

Take a chestnut

What does kangkang middleware look like? As mentioned earlier, middleware is essentially a processing function, so you see a function that looks like this:

async function userMiddleware (req, res, next) {
    try {
        const userData = await getUserData(req.params.id);  //see app.get below

        if(userData) {
                req.user = userData;
                next();
        }
    } catch(error)  {
        res.status(500).send(error.message); //replace with proper error handling
    }
}
Copy the code

Error handling middleware

Error handling middleware such as app.use (Err, REq, RES, Next)

Error-handling middleware always takes four parameters (Err, REq, RES, next). You must identify it as an error-handling middleware function by providing four parameters. Even if you don’t need to use the Next object, you must specify it. Otherwise, the Next object will be interpreted as normal middleware and will be unable to handle errors.

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
Copy the code

Middleware usage

Using app.use to call middleware, you can also link middleware in an array of middleware or by using multiple app.use calls:

app.use(middlewareA);
app.use(middlewareB);
app.get('/', [middlewareC, middlewareD], handler);
Copy the code

When a node receives a request, each middleware matching the request will run in the order it was initialized: middlewareA–> middlewareB –> middlewareC –> middlewareD until there is a termination operation.

conclusion

In a word: Middleware can run code on each request or request for a specific route and take action on request or response data.