stackdave stackdave - 25 days ago 9
Node.js Question

Order of route precedence express 3 vs 4

Accord to a book for express3. In the following case, http://localhost:3000/abcd will always print "abc*", even though the next route also matches the pattern.

My question is work in the same way for express4 ?

app.get('/abcd', function(req, res) {
res.send('abcd');
});
app.get('/abc*', function(req, res) {
res.send('abc*');
});


Reversing the order will make it print "abc*":

app.get('/abc*', function(req, res) {
res.send('abc*');
});
app.get('/abcd', function(req, res) {
res.send('abcd');
});

Answer

The first route handler that matches the route is the one that gets called. That's how Express works in all recent versions. You should generally specify your routes from more specific to less specific and then the more specific will match first and the less specific will catch the rest.

If you want a handler to see all matches and then pass things on to other handlers, you would generally use middleware:

// middleware
app.use("/abc*", function(req, res, next) {
    // process request here and either send response or call next()
    // to continue processing with other handlers that also match
    next();
});
Comments