Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

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

Before submitting a new post, of course, I have to validate the form entries. I use express-validator version 6.3.0.

My addPost controller:

exports.addPost = (req, res, next) => {
    // 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();

    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'));
            }
        });
    }
}

The Post model:

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    short_description: {
        type: String,
        required: true
    },
    full_text: {
        type: String,
        required: true
    },
    post_image: {
        type: String,
        required: false
    },
    updated_at: {
        type: Date,
        default: Date.now()
    },
    created_at: {
        type: Date,
        default: Date.now()
    }
});

The error messages are nor rendered in the view, which looks like this:

<div id="messages" class="text-center">
    <% Object.keys(messages).forEach(function (type) { %>
        <% messages[type].forEach(function (message) { %>
            <div class="alert alert-<%= type %>"><%= message %></div>
        <% }) %>
    <% }) %>
</div>

UPDATE:

The index.js file in the root has this code:

const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const path = require("path");
const morgan = require("morgan");
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressLayouts = require("express-ejs-layouts");
const flash = require("express-flash");
const session = require("express-session");
const app = express();

dotenv.config();

//Conect to MONGODB
mongoose
  .connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("conected");
  });

mongoose.connection.on("error", err => {
  console.log(`DB connection error: ${err.message}`);
});

// Set static directory
app.use(express.static(path.join(__dirname, "public")));

// Set views directory
app.set("views", path.join(__dirname, "views"));

// Set view engine
app.set("view engine", "ejs");

// Use Express Layouts
app.use(expressLayouts);

// Morgan Middleware
app.use(morgan("dev"));

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cookieParser());

// Express Sessions Middleware
app.use(session({
  secret: '123',
  resave: true,
  saveUninitialized: true
}));

// Express Messages Middleware
app.use(flash());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Bring the Dashboard
const dashboardRoute = require("./routes/admin/dashboard");

// Get Dashboard Routes
app.use('/dashboard', dashboardRoute);

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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

<div id="messages" class="text-center">
<% Object.keys(messages).forEach(function (type) { %>
    <% messages[type].forEach(function (message) { %>
        <% if (type === 'errors') {%>
            <div class="alert alert-<%= type %>"><%= message.msg %></div>
        <%} else { %>
            <div class="alert alert-<%= type %>"><%= message %></div>
        <% } %>
    <% }) %>
<% }) %>

I guess this is what you intended to do


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...