Express Router参数验证 [英] Express Router param validation

查看:307
本文介绍了Express Router参数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

express 4x api文档声称您可以将正则表达式作为第二个参数传递给 以便验证参数.

The express 4x api docs claim that you can pass regex as a second argument to router.param in order validate params.

该方法现在可用于有效验证参数(和 (可选)解析它们以提供捕获组)

The method could now be used to effectively validate parameters (and optionally parse them to provide capture groups)

然后提供以下示例.

// 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, this doesn't actually seem to work. Taking a deeper dive, it doesn't look as if the express code actually supports what the docs claim. In fact, passing anything other than a function will get you a tidy invalid param() call exception.

表达4.12.3
节点0.12.4

express 4.12.3
node 0.12.4

所以我的问题是该功能是否确实存在,或者我做错了什么.我正在尝试完成文档中提供的相同操作,但收到上述错误.任何指导将不胜感激:)

So my question is whether this functionality actually exists or if I'm doing something wrong. I'm trying to accomplish the same thing provided in the doc but am receiving the error mentioned above. Any guidance would be greatly appreciated :)

推荐答案

可以找到答案这里.

基本上,如果要使用Express <= 4.11,则需要在之前运行以下代码片段,以利用上述的router.param(fn)方法.

Essentially the following snippet would need to be run prior to leveraging the router.param(fn) method as outlined above if you're using express <= 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之前的示例会弹出弃用警告.

express 4.12

If you're using express >= 4.12 you can accomplish the same without the need of router.param(fn) using the following. In fact, the pre 4.12 example above will pop a deprecation warning.

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

虽然在文档中对此进行了说明,但还不太清楚.
希望这会有所帮助.

While this is stated in the doc, it isn't quite clear.
Hope this helps.

这篇关于Express Router参数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆