Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express default route parameter

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)
{
}
like image 418
timhc22 Avatar asked Dec 07 '15 15:12

timhc22


1 Answers

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 });
like image 173
Joanvo Avatar answered Oct 12 '22 06:10

Joanvo