Joshua.Lim
Joshua.Lim

Reputation: 113

Express JS Routing redirection

Forgive me as I am very new to Node JS / Express JS

I have the following piece of code:

router.get('/:locationId', async (req, res) => {
  console.log('[GET by _id] /locations/')
  try{
    const location = await Location.findById(req.params.locationId);
    res.json(location);
  }catch(err){
    res.json({message:err, status:500});
  }
});


router.get('/location_id/', async (req, res) => {
  console.log('[GET by location_id] /locations/location_id')
});

Every time I call localhost:3000/location_id/, it calls the first function with "location_id" as its parameter.

Am I missing something?

Upvotes: 0

Views: 67

Answers (1)

slebetman
slebetman

Reputation: 113866

Express routes and middlewares are a list/array/stack/queue of functions processed in sequence. Express never rearranges the sequence of routes and middlewares.

You have two routes:

get('/:some_variable')
get('/location_id/')

The first route will always match everything because /location_id is also a valid string that can be assigned to the path variable of the first route.

You can make the routes work by rearranging which route gets processed first:

get('/location_id/')
get('/:some_variable')

Upvotes: 3

Related Questions