Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
URL mapping in node js with express
    router.get("customer/:customerId", async (request, response) => {
        console.log("Fetch customer with a particular customer ID")
    }
    
    router.get("customer/regions", async (request, response) => {
        console.log("Fetch all customers from a region")
    }

But whenever I make any request the request is being served by the first api(the regions is getting considered as customerId) and not the second one.How can we have url mappings in these kind of scenarios?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can handle this problem three ways.

One is to switch the order of your two router.get()s. Express handles them in order. The way you have it, express thinks regions is a customerId.

Another is to append a regexp to your :customerId route parameter. For example, if your customerIds are 12-digit numbers you can do this to prevent that route from handling anything except customer/123456654321-style URLs.

router.get("customer/:customerId(\d{12})", async (request, response) => {
  console.log("Fetch customer with a particular customer ID")
}

A third is to use the next() parameter. It tells express that your route handler refuses the URL, and to move on to try other matching routes.

router.get("customer/:customerId(\d{12})", async (req, res, next) => {
  if (<<it's an invalid customerId>>) return next()
  console.log("Fetch customer with a particular customer ID")
}

You probably should use next() anyway to refuse invalid customerIds, and you should use random hard-to-guess customerId values. Because Panera Bread.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!