I am surprised I can't find this so it has probably been answered before (and I'm searching for the wrong thing).
Basically, is it possible and how do I set a default value on a nodejs express route?
// Test route
router.route('/tests/:id')
.get(testsController.tests.get);
Where if :id
is not set, it will automatically set to an arbitrary value, e.g. 1.
Controller Code:
var testsController = {
tests: {
get: function (req, res, next) {
if (req.params.id) {
res.render('tests.html', { title: 'The Site', id: req.params.id });
next();
} else {
//res.redirect('/')
console.log('here');
}
}
}
};
I know in PHP Symfony2 I can do something like this:
/**
* @Route("/tests/{id}")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function testAction(Request $request, $id=1)
{
}
You are setting it up correctly, but you need to get the parameter afterwards from the request object, it is not passed automatically to the action:
req.params.id
[Edit] To make the parameter optional you should define the route like this:
router.route('/tests/:id?')
.get(testsController.tests.get);
and if you want to set a default value do that:
res.render('tests.html', { title: 'The Site', id: req.params.id || 1 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With