【问题标题】:How to use express validator如何使用 express 验证器
【发布时间】:2020-11-07 00:59:50
【问题描述】:

我需要验证器来检查错误并登录到控制台(如果有)

下面是我的代码;

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;

但我在控制台中的结果是

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

【问题讨论】:

    标签: javascript node.js arrays express validation


    【解决方案1】:

    你应该记录的是

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

    这是在快速验证器docs 中记录错误的正确方法。每当提交包含无效字段的请求时,您的服务器都会做出如下响应:

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

    对于 express-validator 中所有可用的验证器(就像它的选项一样),请查看 validator.js 文档 here

    【讨论】:

      【解决方案2】:

      您可以在您的路由器定义中传递一个数组,该数组包含您希望对给定路由处理的每个请求执行的每个验证。

      喜欢这个

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

      对于您的具体情况,它看起来像这样

      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 
      }
      

      【讨论】:

      • 不客气,当问题有答案时,您必须将其标记为已解决,如果有帮助则为答案投票
      【解决方案3】:

      express 是一个中间件框架 express-validator 用于验证我们需要在实际传递请求之前调用验证器的请求,因为我们使用快速验证器 在回调方法之前,您必须检查验证,您将在回调之前传递一个中间件

      这里你想怎么做

      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);
          }
        }
      );
      

      【讨论】:

        猜你喜欢
        • 2019-09-01
        • 1970-01-01
        • 2020-02-20
        • 2017-02-03
        • 1970-01-01
        • 2022-01-18
        • 2019-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多