Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Low Priority Express.js app.get('/route');

Is there a way to register an express.js app.get() call with a lower priority?

For example,

app.get('*', function(req, res) {});
app.get('/page', function(req, res) {});

Would there be a way to specify a lower priority on that first call so that it is at the bottom of the route lookup, allowing the later called path to be checked first, effectively as if the first line of code was executed after the second line of code?

like image 704
Thomas Hunter II Avatar asked Dec 18 '12 18:12

Thomas Hunter II


People also ask

How can we create Chainable route handlers for a route path in Expressjs?

By using app. route() method, we can create chainable route handlers for a route path in Express.

How does Express handle 404 error?

In Express if we want to redirect the user to the 404 error page if a particular route does not exist then we can use the app. all() method as the last route handler method and * (asterisk) as the route name.

How many middleware can be on a single route?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app.

What does next () do in Express?

The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.


1 Answers

I just had a quick look at Express' source code and it does not seem you can set any kind of priority when you add routes. Routes are always matched by order of creation. In your example, it will first try to match '*', then '/page'.

However, you can ask Express to resume matching after you are done:

app.get('*', function (req, res, next) {
   // run some tests on the request
   // ...

   // finally, resume matching
   next();
});
like image 155
Laurent Perrin Avatar answered Sep 22 '22 22:09

Laurent Perrin