Express —— Middleware and the middleware stack

Please indicate the source of the original reprint: http://agilestyle.iteye.com/blog/2339754

 

Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

 

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

 

The following figure shows the elements of a middleware function call:


 

The middleware stack

The web server usually listens for the request, parses the request, and sends the response. The Node runtime first takes these requests and converts them from raw bytes into two JavaScript objects you can handle: request(req) and response(res). When using only Node.js, the flow chart is shown below.


 

These two objects will be sent to a JavaScript Function you define yourself. You'll parse req yourself to identify what the user wants, and handle res to prepare your response smartly.

After a while, you'll finish writing the response by calling res.end. This res.end tells Node that the response is complete and is ready to be sent. The Node runtime will first look at what you've done with the response object, then convert it into another bundle of bytes that will eventually be sent to the user making the request on the network.

In Node, these two objects are simply passed through a Function. But in Express, these objects are passed through a series of Functions, called the middleware stack . Express will start from the first Function in the stack and execute down the stack, as shown in the figure below.


 

Each function in the Stack takes 3 parameters. The first two are req and res, which are provided via Node; the third parameter of each function is itself a function, called next by convention. When next is called, Express will run the next function in the stack, as shown in the figure below.


 

Finally, a function in Stack must call res.end to end the request (in Express, other methods can also be called, such as: res.send or res.sendFile, but these methods internally call res.end) . You can call res.end of any function in the middleware stack, but you can only call it once, otherwise an error will be reported.

 

Reference

http://expressjs.com/en/guide/writing-middleware.html

Manning.Express.in.Action.Node.applications.with.Express.and.its.companion.tools.2016

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327089280&siteId=291194637
Recommended