5

我们express-validator如何检查请求的查询?

在文档中有一个检查正文的示例:

const { check, validationResult } = require('express-validator/check');

app.post('/user', [
  // username must be an email
  check('username').isEmail(),
  // password must be at least 5 chars long
  check('password').isLength({ min: 5 })
], (req, res) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

如何将其设置为仅检查GET方法查询?

GET /user?username=name 我只想username在这里检查查询。

4

3 回答 3

15

要检查查询参数中的变量,即 req.query,请使用query([fields, message])。与check([fields, message])相同,但只检查req.query

例子:

安装 express-validator

npm install --save express-validator

导入查询

const { query } = require('express-validator/check');

使用查询

router.post('/add-product', 
                isAuth, 
                [
                    query('title')
                        .isString().withMessage('Only letters and digits allowed in title.')
                        .trim()
                        .isLength({min: 3}).withMessage('Title too short. Enter a longer title!'),
                    query('price', 'Enter a valid price.')
                        .isFloat(),
                    query('description')
                        .trim()
                        .isLength({min: 30, max: 600}).withMessage('Description must be of minimum 30 and maximum 600 characters!'),
                ],
                adminController.postAddProduct);

在此处查看官方文档:https ://express-validator.github.io/docs/check-api.html

于 2019-06-29T19:49:10.743 回答
3

您可以通过以下方式实现:

app.post('/user', [
  check.query('username')
], (req, res) => {
 //your code
});
于 2018-08-20T07:35:39.687 回答
1

验证人是 -

const {
    check,
    validationResult
} = require('express-validator');

const fetchStatementValidator = [
    check('startdate').not().isEmpty().withMessage("Start date cannot be empty"),
    check('enddate').not().isEmpty().withMessage("End Date cannot be empty"),
]

module.exports.fetchStatementValidator = fetchStatementValidator;

Api 是 -

router.get("/fetchStatement", auth.adminAuth, validator.fetchStatementValidator, utility.statements.fetchStatement); //fetch statement

API 定义 -

/* Fetch transections */
module.exports.fetchStatement = async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).json({
            success: false,
            errors: errors.array()
        });
    }
};

Api 通过邮递员命中 -

http://localhost:5000/loans/fetchCompletedLoans?page=1&startdate=2019-09-08&enddate=

回复 -

{
    "success": false,
    "errors": [
        {
            "value": "",
            "msg": "End Date cannot be empty",
            "param": "enddate",
            "location": "query"
        }
    ]
}
于 2020-03-20T09:02:08.297 回答