如何解决在Express应用中无法从“ req.params”检索数据
我正在尝试从Express应用程序获取我的数据模型ID。在我的app.js中设置了
app.use('/grades/:id/students',studentRoutes);
因此,当我在任何路由/:student_id/show
文件中使用.js
时,路由应该像
/grades/:id/students/:student_id/show
实际上是这样做的,但是问题是当我尝试获取req.params.id
时,我获取的是null
而不是id
。我可以毫无问题地得到req.params.student_id
。
这是我的学生路线
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);
}
});
});
有人请在这里帮助我!
解决方法
为了访问父路由器的参数,创建子路由器时需要将mergeParams设置为true
:
const router = express.Router({ mergeParams: true })