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

后端 未结 8 2162
轻奢々
轻奢々 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条回答
  •  猫巷女王i
    2020-12-22 03:29

    exports.addPost = (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            req.flash('errors', errors.array())
            req.session.save(() => res.redirect('../addpost'));
            //return res.status(400).send(errors.array());
        } else {
                const post = new Post();
                    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'));
                        }
                });
        }
    }
    

    messages.ejs

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

    I guess this is what you intended to do

提交回复
热议问题