【问题标题】:express-validator with get service具有获取服务的快速验证器
【发布时间】:2020-03-26 13:21:58
【问题描述】:

我想在获取服务中验证我的参数。

我的网址就像 /tableref?param1&param2

我的代码是这样的

app.get('/tableref\?:event&:queryObject', [
check('event').isLength({ min: 5, max:15 }),
check('queryObject').isLength({ max: 5, max:35 })
] , function(req, res) {...})

但我遇到了 404 错误。

我想使用 express-validator 来检查我的参数。 之前,我的代码是

 app.get('/tableref', function(req, res) {...})

如何使用 get query 检查我的参数?提示

【问题讨论】:

    标签: javascript node.js express express-validator


    【解决方案1】:

    您可以按照postput 请求的实现方式执行此操作。
    你应该只导入query验证器

    const { query, validationResult } = require('express-validator/check');
    
    
    app.get("/tableref", 
        [
            query('event').isLength({ min: 5, max:15 }),
            query('queryObject').isLength({ min: 5, max:35 })
        ],
        (req, res, next) => {
            // Check validation.
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return res.status(422).json({ errors: errors.array() });
            }
            return res.status(200).json({message:'valid query params'});
    
    });
    

    您的网址应该是这样的/tableref?event=example&queryObject=anotherexample

    请注意,使用上面的代码,您的查询参数是必需的。如果你省略一个,你会得到一个错误。
    如果您希望您的任何参数是可选的,您必须添加 optional 方法

    query('queryObject')
    .optional({checkFalsy: true}).isLength({ min: 5, max:35 })
    

    这样,/tableref?event=example 请求就相当有效了。

    【讨论】:

    • 感谢您的回复,但这意味着我必须更改在客户端调用 url 的方式。没有其他解决办法吗?
    • 你能给我一个请求url的例子吗?
    • 喜欢这个 /tableref?TEST1&Table_test
    • 如果我理解得很好,TEST1 和 Table_test 将是动态值。因此,您可以将它们用作值而不是键。示例/tableref?event=TEST1&queryObject=Table_test
    猜你喜欢
    • 2015-10-01
    • 2020-09-29
    • 1970-01-01
    • 2013-05-03
    • 2016-10-13
    • 2017-09-24
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多