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

后端 未结 8 2138
轻奢々
轻奢々 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:34

    I have applied the solution provided by Saravanakumar T N with a small modification in messages.ejs.

    I have: this in the controller:

    exports.addPost = (req, res, next) => {
      const errors = validationResult(req);
      const post = new Post();
      if (!errors.isEmpty()) {
        req.flash('danger', errors.array());
        req.session.save(() => res.redirect('../addpost'));
     } else {
        post.title = req.body.title;
        post.short_description = req.body.excerpt
        post.full_text = req.body.body;
    
        post.save(function(err) {
            if (err) {
                console.log(err);
                return;
            } else {
                req.flash('success', "The post was successfully added");
                req.session.save(() => res.redirect('/dashboard'));
            }
        });
      }
    }
    

    In the view:

    <% Object.keys(messages).forEach(function (type) { %> <% messages[type].forEach(function (message) { %>
    <% if (type === 'danger') { %> <%= message.msg %> <%} else { %> <%= message %> <% } %>
    <% }) %> <% }) %>

提交回复
热议问题