gpt4 book ai didi

node.js - express-validator:如何检查查询

转载 作者:太空宇宙 更新时间:2023-11-03 22:41:08 26 4
gpt4 key购买 nike

使用 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/用户?用户名=名称我只想在此处的查询中检查用户名

最佳答案

要检查查询参数(即 req.query)中的变量,请使用 query([fields, message])。与 check([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

关于node.js - express-validator:如何检查查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51924864/

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