gpt4 book ai didi

node.js - 快速路由器参数验证

转载 作者:IT老高 更新时间:2023-10-28 23:26:05 26 4
gpt4 key购买 nike

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

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]);
});

但是,这实际上似乎不起作用。进行更深入的研究,它看起来不像 express code实际上支持文档声称的内容。事实上,传递函数以外的任何东西都会给你一个整洁的 invalid param() call 异常。

使用

表达4.12.3
Node 0.12.4

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

最佳答案

答案可以在here找到.

基本上需要在之前运行以下代码段才能利用 router.param(fn)如果您使用的是 express <= 4.11,请使用上述方法.

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');
}
}
}
});

express 4.12

如果您使用的是 express >= 4.12您可以完成相同的操作而不需要 router.param(fn)使用以下。事实上,上面 4.12 之前的示例会弹出弃用警告。

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

虽然这在文档中有所说明,但不是很清楚。
希望这会有所帮助。

关于node.js - 快速路由器参数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30471369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com