Validating Express Router Settings

The 4x api docs express states that you can pass a regular expression as the second argument router.paramto check for parameters.

Now the method can be used to effectively check parameters (and not necessarily analyze them to provide capture groups)

He then provides the following examples.

// validation rule for id: should be one or more digits
router.param('id', /^\d+$/);

router.get('/user/:id', function(req, res) {
  res.send('user ' + req.params.id);
});

// validation rule for range: should start with one more alphanumeric characters, followed by two dots, and end with one more alphanumeric characters
router.param('range', /^(\w+)\.\.(\w+)?$/);

router.get('/range/:range', function(req, res) {
  var range = req.params.range;
  res.send('from ' + range[1] + ' to ' + range[2]);
});

But it doesn’t actually work. Accepting a deeper dive, it seems that the express code actually supports what the documents require. In fact, passing anything other than a function will give you a neat exception invalid param() call.

Via

express 4.12.3
node0.12.4

, : - . , , , . :)

+4
1

.

, router.param(fn), , <= 4.11.

4.11

router.param(function(name, fn) {
  if (fn instanceof RegExp) {
    return function(req, res, next, val) {
      var captures;
      if (captures = fn.exec(String(val))) {
        req.params[name] = captures;
        next();
      } else {
        next('route');
      }
    }
  }
});

4.12

>= 4.12, router.param(fn), . , 4.12 .

app.get('/user/:userId([0-9]+)', fn);

, . , .

+1

All Articles