How does app.use know when it is a string route?

Question

how does app.use know when it is a string route?

Answer

app.use() doesn’t exactly know that it is dealing with a route, it only sets up the middleware to use on each request, as we can see from this answer, app.use() adds objects to an array of middleware. What it does know is where to place what it receives.

As we know when we write a function, we set if we need it to receive any specific data, for example:

function dataLogger(data){
  console.log('this is data: ', data);
}

there we made a function called dataLogger that takes an argument data and logs is, the same way, the use method was set with two parameters, the first one(optional) a path and the second a middleware callback function that will be called upon request, and so a possible visual can be:

function use(path = '', callback){
  ...
}

check that I assigned path an empty string. Most likely something like that was done, which assigns the empty string if there is no path argument being passed and therefore placing the callback middleware to run at every single request. The use method does not know it is a route, it only knows if it receives a path or not, and it places it in an object next to the callback:

const middleware = [];
...
express.use(path = '', callback){
 
  let middlewareObj = {
      route: path,
      handle: [callback]
  }

//and then join the current middleware array
  middleware.push(middlewareObj);
}

that could be a probable way on how .user() looks, but the ones in charge of checking each string path received against the routes in that (for example purposes only) middleware array, are the request methods get, put, delete, all, etc. which really just grab the string received as argument and compare it to the route values in the object array until there is a match or multiple, and runs those middleware functions from the matching route to process the request and elaborate the response.

1 Like