0

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!

prashant
  • 127
  • 2
  • 10
  • Can you try placing the second `router.get` before the first one? That is, having the more specific variant first, so it'll get matched earlier by express. – Horia Coman Jan 17 '18 at 15:20
  • Why you would use regex ? – YouneL Jan 17 '18 at 15:25
  • @HoriaComan, I tried this. But it is not working. It is still calling /user/list api when i call /user/AS123D api – prashant Jan 17 '18 at 15:30
  • @prashant you should use it without the regex. So just `"/user/list"` as the first configuration and `"/user/:id"` as the second. – Horia Coman Jan 17 '18 at 15:32

1 Answers1

1

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 ---");
});