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

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

    it's not a bug with express-validators, it is the way how validators work in case of middlewares.

    At the root level create a directory called utils and inside the directory a validation.js file and add your validation code in it:

    utils/validation.js

    const { check } = require('express-validator');
    exports.addPostCheck = [
        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()
    ];
    

    In the routes/dashboard.js include validation.js

    const validator = require('../../utils/validation.js');
    
    Change Line No: 16
    From: 
    router.post('/post/add', dashboardController.addPost);
    To:
    router.post('/post/add', validator.addPostCheck, dashboardController.addPost);
    

    In the controllers/admin/dashboard.js

    Change Line No: 2
    From: 
    const { check, validationResult } = require('express-validator');
    To:
    const { validationResult } = require('express-validator');
    
    Remove Line Nos 29 to 39.
    

    Reference

提交回复
热议问题