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

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

    from what i see in the documentation of express-validator you need to provide an array of validation rules(those checks at the top of your controller) when you define the route. It doesn't make much sense for them to be at the top of the request handler since the express-validator won't be able to access the context that provides the request to be validated.

    So in the router you need something like this:

    router/front-end/posts.js

    const validationRules = [// Form validation rules
            check('title', 'The title field id required')
            .not()
            .isEmpty(),
        check('excerpt', 'The excerpt field id required')
            .not()
            .isEmpty(),
     check('body', 'The full text field id required')
            .not()
            .isEmpty()];
    // create new post
    router.post('/', validationRules, postsController.addPost);
    

    controllers/front-end/posts.js

    exports.addPost = (req, res, next) => {
    
            const errors = validationResult(req);
    
            if (!errors.isEmpty()) {
                console.log(errors.array());
         }
    
            if (!errors.isEmpty()) {
                res.render('admin/addpost', {
                layout: 'admin/layout',
                 website_name: 'MEAN Blog',
                 page_heading: 'Dashboard',
                 page_subheading: 'Add New Post',
                 errors: errors
                });
                req.flash('danger', errors);
                req.session.save(() => res.redirect('/dashboard'));
            } 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'));
                            }
                    });
            }
    }
    

    Everything else seem ok, at least from the code you posted.

提交回复
热议问题