'expressjs repo documentation

I want to understand the internal working of Expressjs (just curious). Much of the thing are clear but I am not able to understand the chaining of routing and middleware. How expressjs add all the route and middleware to path / and how it keep the stack of route with middleware internally

So I will be very thankful to you if you provide some documentation or link from where I get the understanding how expressjs work internally

Thanks



Solution 1:[1]

ExpressJS is just an HTTP server allowing you to route and manipulate the received requests and returning a response.

So if you carefully look at the HTTP packet format below,

HTTP Packet

you can find the method and the path in the first line.

So, basically here express-router has a regex matcher that tries to match the HTTP request it receives to the predefined routes declared in the express application.

If you check L:43 Router, here it shows that the route you declare is just a function containing 3 constants:

  1. path - That would be a path to match.
  2. stack - Following a proper format, the URL is broken down using the / separator and a stack is formed in order of it's parsing, comprising another function called layer.
  3. methods - Methods are the HTTP methods that we declare along with the path.

Parsing

So when a request is made, let's suppose: http://localhost:8000/user/1/test

  1. We get the path: /user/1/test
  2. The router's handle function is executed. Then this path is broken down into layers and formed a stack: ['user', '*', 'test']
  3. This stack is then matched with that of the route objects that are pre-declared in the application and are used as Route functional objects.
  4. As soon as it finds the match the callback is executed!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Trishant Pahwa