Val*_*eri 4 node.js express express-validator
随着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));
});
Run Code Online (Sandbox Code Playgroud)
如何将其设置为仅检查GET
方法查询?
GET /user?username=name
我只想username
在这里检查查询。
小智 13
要检查查询参数中的变量,即 req.query,请使用query([fields, message])。与check([fields, message]) 相同,但只检查req.query。
安装快速验证器
npm install --save express-validator
Run Code Online (Sandbox Code Playgroud)
导入查询
const { query } = require('express-validator/check');
Run Code Online (Sandbox Code Playgroud)
使用查询
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);
Run Code Online (Sandbox Code Playgroud)
请参阅此处的官方文档:https : //express-validator.github.io/docs/check-api.html
您可以通过以下方式实现这一目标:
app.post('/user', [
check.query('username')
], (req, res) => {
//your code
});
Run Code Online (Sandbox Code Playgroud)