Jeremy Nelson
Jeremy Nelson

Reputation: 286

Express router uses different route when adding param

I have two routes

I'm trying to access /name and pass the name param. It hits the /name route when I have the endpoint as just /name with no parameter, but when I change it to '/name/:name' to get the param, it switches and starts to use the '/:id' route

router.get('/name/:name', (req, res, next) => {
  console.log('called name',req.params.name )
  Project.findOne({name:req.params.name}).then(results => {
    res.json({"project": results})
  })
})

router.get('/:id', (req, res, next) => {
  console.log('called id')
  Project.findOne({_id:req.params.id}).then(results => {
    res.json({"project": results})
  })
})

when I take away ':name' it uses the name route, but when I add it back it uses the Id.

Upvotes: 0

Views: 32

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

I guess you misunderstood how routes work. Check out this mdn page for more information.

/name/:name will match any a route like /name/.* that means it will match anythyng if it has /name/ as prefix, i.e /name/xyz.

:name is a PLACEHOLDER. Which means whatever you put after /name/ it is accessible by the req.params.name variable.

Now for your example, when you are hitting /name:name it is not matching the /name/.* pattern so it goes to the next route. which is /:id means /.* which is effectively any route.

Upvotes: 1

Related Questions