我正在使用Express,EJS和MongoDB开发 博客应用程序 (单击链接以查看 GitHub存储 库)。
当然,在提交新帖子之前,我必须 验证表单条目 。我使用 快递验证器 版本6.3.0。
我的addPost控制器:
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')); } }); } }
邮政模型:
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() } });
错误消息也不会在视图中呈现,如下所示:
<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>
更新:
根目录中的index.js文件具有以下代码:
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);
我究竟做错了什么?
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> <% } %> <% }) %> <% }) %>
我想这就是你打算做的