Search code examples
node.jsexpressexpress-router

Express router regex issue


I am using express router in my project, I am facing following problem,

I have 2 routes as follows

router.get("/user/:id", (req, res) => {
  console.log("---- ABCD ---");
});

router.get("/user/list", (req, res) => {
  console.log("---- PQRS ---");
});

When i call, http://localhost:3000/user/list api, ABCD is printed in console instead of PQRS.

I know we can write regex in router to handle this situation. I tried with following code.

router.get("/user/:id(!list$)", (req, res) => {
   console.log("----- ABCD ----");
}

After making this change, /user/:id api stop working. But /user/list api is working

Please let me know, If I am doing something wrong. Thanks!


Solution

  • The issue is not with regex but. Reorder your route definition so that the dynamic routes are at the bottom. See the code below

    router.get("/user/list", (req, res) => {
      console.log("---- PQRS ---");
    });
    
    router.get("/user/:id", (req, res) => {
      console.log("---- ABCD ---");
    });