Home > Software design >  Two routes use params but only one is working
Two routes use params but only one is working

Time:05-17

I'm trying to make a website that show you all the restaurants in the country with all th different cities. I add a route for restaurants that use params to redirect you to the restaurant page.

router.get('/:name',checkUser, async (req, res) => {

    try {
        
        const wila = await wilaya.findOne({nom : req.params.name})
        const re = await restaurant.find({ville : wila.nom})
        
        res.render('html/villeDetails', {
        wilay: wila,
        title : wila.nom,css : "villeDetails",
        resto : re
        })
    } catch {
        res.redirect('/')
    }
    })

And another route that also use params to take you to the city details page

router.get('/:id',checkUser, async (req, res) => {
  
    try {
      console.log('here')
      const resto = await restaurant.findById(req.params.id)
      comment.find({resId : req.params.id})
      .then((result) => {
        res.render('html/restaurantDetails', {
        res: resto,
        title : resto.nom,
        css : "restaurantDetails",
        comm : result
        
      })
      })
    } catch {
      res.redirect('/')
    }
  })

The problem is that only the restaurant route is working and when i delete the restaurant route, the city route start working . i don't know why this is happening .

CodePudding user response:

/:name and /:id are both on the same route(/). I have noticed that when this happens only the route that is seen first (/:name) would be recognised. You can try changing the route for one of them like /:name for the restaurant route and /restaurant/:id for the city route.

CodePudding user response:

Yes. When you use named path parameters like /:id, /:name or /:post_id what you are doing id telling the express router that you are going to pass "something" in that segment of the URI and that you'd like for that be stored in a variable with that name. It doesn't know whether you are passing an id or a name or something else. Use nested routes for this purpose. I'd recommend you check this guide

  • Related