使用express-validator,我们如何检查请求的查询?
在文档中有一个检查body的示例:
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方法的查询?
我只想在这里检查查询中的username。
发布于 2018-08-20 15:35:40
您可以通过以下方式实现此目的:
app.post('/user', [
check.query('username')
], (req, res) => {
//your code
});发布于 2019-06-30 03:49:11
要检查查询参数中的变量,即查询,请使用 req.query (fields,message)。与(fields,message)相同,但仅检查req.query。
示例:
安装快速验证器
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
发布于 2020-03-20 17:02:08
验证器是-
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接口定义-
/* 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"
}
]
}https://stackoverflow.com/questions/51924864
复制相似问题