Search code examples
node.jsexpressexpress-router

Express router calls the wrong route


So, I have an API with with a few routes defined (I'm not going to list all of them) where one of them never gets called unless I change it's name.

this is how I define them in code:

// Each middleware/function is separated by commas ofcourse
app.route('.../a/b/:params')
.get(someMiddlewares, someFunctions); 

app.route('.../a/b/c')
.get(someOtherMiddlewares, someOtherFunctions);

I what I noticed is that, since the first route is defined as ".../a/b/:params" and the second as ".../a/b/c", the first one allways gets called instead.

I have looked through a lot of questions and I have yet to find an answer or anyone with a similar enough problem and would like to know what I can do to fix this instead of just renaming routes.

Thank you in advance.


Solution

  • .../a/b/:params means .../a/b/.* in terms of regex. As, .../a/b/c also matches this pattern it is expected behaviour to call the first functions.

    Just put the .../a/b/c on top of the .../a/b/:params route.

    app.route('.../a/b/c')
    .get(someOtherMiddlewares, someOtherFunctions);
    
    app.route('.../a/b/:params')
    .get(someMiddlewares, someFunctions); 
    

    So that /a/b/c is matched first.