简体   繁体   English

如何使用快速验证器

[英]How to use express validator

i need validator to check for error and log into console if any我需要验证器来检查错误并登录到控制台(如果有的话)

here is my code below;下面是我的代码;

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

router.post('/add-page', function(req, res){
check("title", "Title must have a value.").not().isEmpty();
check("content", "Content must have a value.").not().isEmpty();


var title = req.body.title;
var slug = req.body.slug.replace(/\#+/g, "-").toLowerCase();
if (slug == "") {
    slug = title.replace(/\#+/g, "-").toLowerCase();
}

var content = req.body.content;
var errors = validationResult(req);
if (errors){
    console.error(errors);
    
    
    res.render("admin/add_page",{
        errors: errors,
        title:title,
        slug:slug,
        content:content
    });
} else {
   Page.findOne({slug:slug}, function(err, page){
       if (page) {
           req.flash("danger","Page slug exists, choose another.");
           res.render("admin/add_page",{
            
            title:title,
            slug:slug,
            content:content
        });
       } else {
           var Page = new Page({
               title:title,
               slug:slug,
               content:content,
               sorting:0
           });
           Page.save(function(err){
               if (err) {
                   return console.log(err);
                   
               } else {
                   req.flash("Success", "Page added!");
                   res.redirect("/admin/pages");
               }
           })
       }
   })
    
}

});



//Exports
module.exports = router;

But my result in console is但是我在控制台中的结果是

Result { formatter: [Function: formatter], errors: [] }

What you should be logging is你应该记录的是

if (!errors.isEmpty()) {
   console.log(res.status(422).json({ errors: errors.array() }));
 }

This is the correct way of logging errors in express validator docs .这是在快速验证器文档中记录错误的正确方法。 Whenever a request that includes invalid fields is submitted, your server will respond like this:每当提交包含无效字段的请求时,您的服务器将像这样响应:

{
 "errors": [{
   ... //fields
  }]
}

For all the available validators in express-validator (just like its options), take a look at validator.js docs here .对于 express-validator 中所有可用的验证器(就像它的选项一样),请在此处查看 validator.js 文档。

express is a middleware framework express-validator is used to validate the request for that we need to call the validator before the request is actually passed for that we use express validator before the callback method you have to check for the validation for that you will pass a middleware before the callback express 是一个中间件框架 express-validator 用于验证请求,我们需要在请求实际通过之前调用验证器,因为我们在回调方法之前使用 express 验证器,你必须检查你将通过的验证回调前的中间件

here how you suppose to do that你应该怎么做

router.post(
  "/add-page",
  [
    check("title", "Title must have a value.").not().isEmpty(),
    check("content", "Content must have a value.").not().isEmpty(),
  ],
   (req, res) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        console.log(errors);//if client get any error the code will pass here you can do anything according to your choice
        });

      } catch (err) {
      console.log(err);
    }
  }
);

You can pass in your router definition an array of every validation which you want to perform on each request which is handle by a given route.您可以在路由器定义中传递一个数组,其中包含您要对给定路由处理的每个请求执行的每个验证。

like this像这样

router.post(route_path, [...], function(req, res) {});

For your specific case It will look like this对于您的具体情况,它看起来像这样

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

const router = express.Router();

router.post('/add-page', [
    check("title", "Title must have a value.").not().isEmpty(),
    check("content", "Content must have a value.").not().isEmpty()
], function(req, res) {
    const errors = validationResult(req);
    if(!errors.isEmpty()) {
        console.log(errors);


        return res.status(500).json({
            errors
        });

        /*
        return res.render("admin/add_page",{
            errors: errors,
            title:title,
            slug:slug,
            content:content
        });
        */
    }

    // And the other code goes when validation succeed 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM