I m working on NodeJs application it's Blog application. and i used express Validator,i am trying to validateData with flash message before save posts in database with express flash message in UI side, i successfully save data in database but message is not appear in UI side after submitting forms I gets flash error like this [object Object],[object Object],[object Object]
I am using pug template engine.
const express = require("express");
const path = require("path");
const app = express();
const mongoose = require("mongoose");
const Article = require("./models/article");
const bodyParser = require("body-parser");
const { check, validationResult } = require("express-validator");
const flash = require("connect-flash");
const session = require("express-session");
//Express Session Middleware
app.use(
session({
secret: "keyboard cat",
resave: true,
saveUninitialized: true
})
);
app.use(flash());
app.use((req, res, next) => {
res.locals.errors = req.flash("error");
res.locals.successes = req.flash("success");
next();
});
app.get("/articles/add", (req, res) => {
res.render("add_articles", {
title: "Add Articles"
});
});
// Add Submit POST Route
app.post(
"/articles/add",
[
check("title", "Title is required")
.not()
.isEmpty(),
check("author", "Author is required")
.not()
.isEmpty(),
check("body", "Body is required")
.not()
.isEmpty()
],
(req, res) => {
const errors = validationResult(req);
if (errors) {
res.render("add_articles", {
title: "Add Articles",
errors: errors
});
} else {
//GetErrors
let article = new Article();
article.title = req.body.title;
article.author = req.body.author;
article.body = req.body.body;
article.save(err => {
if (err) {
console.log(err);
return;
} else {
req.flash("success", "Article Added");
res.redirect("/");
}
});
}
}
);
.messages
each type in Object.keys(messages)
each message in messages[type]
div(class="alert alert-"+type) #{message}
.container
if successes
for success in successes
div.alert.alert-success #{ success }
if errors
for error , i in errors
div.alert.alert-danger #{ error }
any help is highly appreciated..
1) The first thing that I would like to notice is about the way you check whether any validation error exists:
const errors = validationResult(req); if (errors) {...}
Should be replaced with:
const errors = validationResult(req); if (errors.isEmpty()) {...}
2) There's also another problem, related to getting array of errors. Instead of:
res.render("add_articles", { title: "Add Articles", errors: errors });
You need to use:
res.render("add_articles", { title: "Add Articles", errors: errors.array() });
Source: Express validator docs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.