How does express know when it found the correct route?

Question

How does express know when it found the correct route?

Answer

When express is set up by creating your methods, and having app.listen(), express itself creates a map of the string routes correlated to each method.
it can be exemplified as so:

{
  get: '/',
  get: '/another-route',
  get: '/expressions',
  post: '/expressions',
   etc...
}

So when a request comes through with a url /expressions and a header method GET, as we see in the graphic from the lesson, it will go through the get request methods and check if the first parameter (string route) matches the url of the request.

//for example if we were to say
const param = '/expressions';
const url = req.url;  //which is /expressions
url === param ? ... : ...;

If so, it will run the get method that matches by passing the request parameters to the request object in the callback function, from there it is up to what we wrote inside to perform the action for a response.

5 Likes