express-validator:如何检查查询

express-validator: how to check queries

使用 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

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

app.post('/user', [
  check.query('username')
], (req, res) => {
 //your code
});

要检查查询参数中的变量,即 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

验证器是 -

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 通过 Postman 命中 -

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"
        }
    ]
}