Express.js application bug: validationResult(req) method does not work

后端 未结 8 2149
轻奢々
轻奢々 2020-12-22 02:38

I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.

Before submitting a

8条回答
  •  暖寄归人
    2020-12-22 03:07

    try change your if statement from this:

       if (!errors.isEmpty()) {
            console.log('there are no validation errors');
        } else {
            console.log(errors);
        }
    }
    

    to this:

        exports.addPost = (req, res, next) => {
            // Form validation rules
            check('title', '')
              .not()
              .isEmpty();
            check('excerpt', '')
              .not()
              .isEmpty();
           check('body', '')
              .not()
              .isEmpty();
    
            const errors = validationResult(req);
    
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
               console.log(errors.array());
            }
    }
    

    Edit

    If you would like to send an response to your front-end replace the console.log() command into res.send() then parse the answer in your front-end like so:

    if (!errors.isEmpty()) {
               return res.send(errors.array());
             // can also send an status and catch it
            // by sending res.status(400).send(errors.array());
            }
    

    Hopefully this makes sense

提交回复
热议问题