What is the working principle of the Node.js middleware?

This article mainly introduces what is the working principle of the Node.js middleware. It has certain reference value, and the friends need can refer to it. I hope that everyone has a big gain after reading this article. Let’s take a look at you with everyone.

What is an Express middleware?

  • The middle piece means anything you are placed in the first floor of the software and the middle of the other.
  • The Express middleware is a function executed in the life cycle of the Express server request.
  • Each middleware can access HTTP requests and responses of all routes attached.
  • Additionally, the middleware can terminate the HTTP request, or it can be passed to another middleware function with next to NEXT. This “chain” of the middleware allows you to divide the code and create reusable middleware.
Writing the requirements of the EXPRESS middleware

You need to install something to create, use, and test the Express middleware. First, Node and NPM are required. To ensure installed, you can run:

NPM -V && Node -V
   You should see installed Node and NPM version . If an error occurs, you need to install Node. All examples should be used under Node Ver 8+ and NPM Ver 5+. 
This article uses Express 4.x. This is important because there is a major change from version 3.X to 4.x.

Express Middleware: Basis

First we use Express’s most basic built-in middleware. Create a new project and npm to initialize it …

NPM INITNPM Install Express –savecreate Server.js and Paste the FOllowing code: const express = Require (‘express “; const app = expression (); app.get (‘ / ‘, (req, res) => {res. extend (‘ welcome Home”;}) App.Listen (3000);

What is the problem solves in the middleware? Why use it?

Hypothesis You running a web application using Node.js and Express
 on the web server. In this application, you need to log in some pages.   When the web server receives a data request, Express will provide you with a request object, which contain information about the user and its requesting data. Express also allows you to access response objects, you can modify it before the web server responds to users. These objects are usually shortened to 
Req ,



The middleware function is an ideal place for modifying REQ and


and REQ . For example, after the user is logged in, you can get its user details from the database and then store these details in Res.user .

What is the middleware function?

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 prot error handling}} If an error occurs, And you don’t want to perform other code, don’t call the function. Remember to send a response in this case, otherwise the client will wait until the timeout.

VAR App = Express (); // Your Normal Route Handlersapp.get (‘/ user /: id’, usermiddleware, usercontroller);

  Intermediates Chain  
You can link middleware in an intermediate unit or by using multiple app.use


  app.use (middleWarea); app.u ('/', [middleWarec, middlewARED], handler);  

Express receives the request Each middleware that matches the request will be run in the order of initialization until termination operation is terminated.

Therefore, if an error occurs, all middleware used to handle errors will be called in order until one is no longer call next ()

Function calls.
 Express Middleware Type   
Router-level middleware, for example: Router.Use

built-in middleware, for example: Express.Static, ExprEss.json, Express.urlenCoded

Error handling middleware, for example: App.use (Err, Req, Res, NEXT) Node.js中间件的工作原理是什么

Third-party middleware, for example: BodyParser, CookieParser

Router-Level Middleware

Express.Router uses the Express.Router class to create a modular and installable routing process. Routing instances are a complete middleware and routing system.

    You can use middleware for logging, authentication and other operations. As shown below to record the latest activities of the user and parse the authentication header, use it to determine the currently logged in user and add it to the Request object.
  • This function is executed when the program receives the request each time. If there is an error, it will only end the response without calling subsequent middleware or routing processing.
  • VAR ROUTER = Express.Router () // load router-level middleware by using the router.use () And Router.Method () functions.//The following example creates a router as a module, loads a middleware function in it, // defines some routes, and mounts the router module on a path in the main app.var express = require ( ‘express’); Var router = express.Router (); // a Middleware Function with no mount path.This Code Is Executed for // Every Request To The Router // Loggingasync Function LogmiddleWare (Req, Res, Next) {Try {Console.log (Req.user.Id, New Date ()); Next ();} catch ) {RES.STATUS (500);}} // Authentication async function checkauthentication (req, res, next) => {// check header or url parameters or post parameters for tokenst token = Req. Body.token || Req.Query.token || Req.Headers [‘x-access-token’] || Req.Headers [‘Authorization’]; if (token) {Try {// Verifies Secret Req.Decoded = AWAIT JWT.VERIFY (TOKEN, Config.secret) let checkuser = await authenticateTokenHelper.getuserdetail (req); // if everything is good, save to request for use in other routesIf (checkuser) {req.user = req.decoded next ()} else {return res.status (403) .json ({message: responsemessage.noauthorized})}}} catch (err) {Return Res.Status (401) .json ({message: responseMessage.invalidToken})}} else {// if there is no token return res.status (400) .json ({message: responseMessage.invalidRequest})}} router.use (logMiddleware); router
    • Express has the following built-in middleware function:
    • Express.Static
    Provides static resources, such as HTML files, images, and the like.
Express.json Load parsing requests with JSON.
  Express.urLENCODED  parses the imported payload request with URL encoding. 
Error Processing Middleware
Error handling middleware always adopts four parameters


. You must identify the middleware function by providing four parameters. Even if you don’t need to use a Next object, you must also specify. Otherwise, the next object will be interpreted as a regular middleware and will not process an error. Basic signatures are as follows:
  • App.use (Function (Err, Req, Res, NEXT) {Console.Error (Err.stack) Res.status (500) .send “Something Broke! ‘)} Example 1:
  • app.get (‘ / users”, (Req, res, next) => {next (‘I am passing you an error!));}); app.use ((Err, Req, Res, next) => {Console.log ERR); if (! res. headerssent) {res.status (500);};
  • In this case, the tip end Error handling middleware will process the error. You may also notice that I check
  • Res. HeadersSnt
property. This is just checking whether the header has sent the header to the client. If not yet, it will send HTTP 500 status and error messages to the client.
Example 2:

You can also link error handlingMiddleware. Different types of errors are usually handled in different ways:

App.get (‘/ users, (Req, res, next) => {let err = new error (‘ i couldn \ ‘t find it.’); err.httpStatuscode = 404; Next (err);}; app.get (‘/ user, (req, res, next) => {let err = new error (‘ i \ ‘m sorry, you can \’ T do That, Dave. ‘); err.httpstatuscode = 304; Next (Err);}; app.use ((Err, Req, Res, next) => {// handles NOT Found Errors if (Err.httpStatusCode === 404) {res.status (400) .render (‘notfound’);} // handles unauthorized errors else if (err.httpstatuscode === 304) {res.status 304) .render (‘unauthorized’);} // catch all else if (! Res. headerssent) {res.status (Err.httpStatuscode || 500) .render (‘unknowner’);} next (err);}
   In this case, the middleware checks whether to throw 404 (Not found) errors. If so, it will render "NOTFOUND "Template page, then pass the error to the next in the middleware. 
The next middleware checks whether to throw a 304 (unauthorized) error. If so, it will render the” unauthorized “page, The error is passed to the next middleware in the pipe.

Finally, “catch all” error handling only error, if no response is sent, it will send an error HttpStatusCode (if not provided, send HTTP 500 State) and rendering “unknownerror” template.

Intermediate Parts
 in some cases, we will add some additional functions to the rear end. First install NODE first The .js module gets the desired function, then load it into your application at the application level or router level.   Example: When the Body-Parser processes the Content-Type request header, all middleware is Packing using the parsing 
Req.Body .

const express = Require (‘express’); const bodyparser = required (‘body-parser’) Const App = Express (); app.use (BodyParser.urlencoded ({extended: false}) app.use (bodyparser.json ()) app.post (‘/ save “, (req, res) => { Res. Json ({“status”: true, “payload”: req.body}} app.listen (3000, (req, res) => {console.log (‘server running on port’)}

Thank you can read this article carefully. I hope that Xiaobian share the working principle of the Node.js middleware. What is helpful, and I also hope that everyone will support Tumi Clouds, pay attention to Tumi Cloud Industry information channel, I will find TUMI clouds in trouble, detailed solutions are waiting for you!

© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment