Search code examples
javascriptnode.jsexpresspostmanreq

My req.params.id is undefined. How can I fix my route to make it work


I am testing my function getIndividualTwitt on Postman and getting undefined when I console.log the req.params.id. This is happening exclusively in this route. I would appreciate any help that you could apare.

index.js

app.use(express.json())

app.use('/profiles',require('../Server/routes/profile'))
app.use('/users',require('../Server/routes/users'))
app.use('/dashboard',require('../Server/routes/dashboard'))

routes/profiles.js

router.post('/:name',authorization,controller.createProfile)
router.get('/:id',authorization,controller.getProfile)
router.delete('/:id',authorization,controller.deleteProfile)
router.get('/twitt/:id',controller.getIndividualTwitt)

controllers/profiles.js

getIndividualTwitt:async(res,req)=>{
  try {
    console.log('hello')
    console.log(req.params.id) //prints undefined
    //const twitt=await connectTwitt.getTwitt(req.params.id)
       
    //res.send(twitt)
  } catch (error) {
    console.log(error)
  }
}

Postman request:

GET  http://localhost:3002/profiles/twitt/8

Solution

  • Problem

    The problem is in the order of your defined endpoints. Express execute code from top to bottom, so when you call /profiles/twitt/8 endpoint. it will find a match in the following router config:

    router.get('/:id',authorization,controller.getProfile)
    

    Solution

    Reverse the order of defined endpoints, like this:

    router.get('/twitt/:id',controller.getIndividualTwitt)
    router.get('/:id',authorization,controller.getProfile)