Sravan SS
Sravan SS

Reputation: 79

Trouble retrieving data from 'req.params' in Express app

I am trying to get my ID of a data model from Express app. In my app.js I've set

app.use('/grades/:id/students', studentRoutes);

So when I use /:student_id/show in any routing .js file the route should come like /grades/:id/students/:student_id/show which actually it does but the problem is when I tried to get req.params.id I'm getting null instead of getting id. I was able to get req.params.student_id without any issues.

Here is my studentRoute

router.get('/:student_id/show', (req, res) => {
  Student.findById(req.params.student_id, (err, foundStudent) => {
    try {
      res.render('students/show', {
        student: foundStudent,
        path: 'student',
        class_id: req.params.id,
      });
      console.log(req);
    } catch (err) {
      res.redirect('back');
      console.log(err);
    }
  });
});

Someone please help me here!!

Upvotes: 0

Views: 85

Answers (1)

antonku
antonku

Reputation: 7665

In order to access params of the parent router, it's required to set mergeParams to true when creating a child router:

const router = express.Router({ mergeParams: true })

Upvotes: 1

Related Questions