gpt4 book ai didi

javascript - 为什么我在 UI 中没有收到验证 Flash 消息,我收到这样的 Flash 错误 [object Object],[object Object],[object Object]

转载 作者:行者123 更新时间:2023-12-02 22:42:21 31 4
gpt4 key购买 nike

我正在开发 NodeJs 应用程序,它是博客应用程序。我使用了快速验证器,我尝试在 UI 端使用快速闪存消息将帖子保存在数据库中之前使用闪存消息验证数据,我成功地将数据保存在数据库中,但在提交表单后消息未出现在 UI 端我收到这样的闪存错误[对象对象],[对象对象],[对象对象]

我正在使用哈巴狗模板引擎。

app.js

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("/");
}
});
}
}
);

消息.pug

.messages
each type in Object.keys(messages)
each message in messages[type]
div(class="alert alert-"+type) #{message}

布局.pug

 .container
if successes
for success in successes
div.alert.alert-success #{ success }
if errors
for error , i in errors
div.alert.alert-danger #{ error }

非常感谢任何帮助..

最佳答案

1)我想注意的第一件事是检查是否存在验证错误的方式:

const 错误=validationResult(req);如果(错误){...}

应替换为:

const 错误=validationResult(req); if (errors.isEmpty()) {...}

2) 还有另一个问题,与获取错误数组有关。而不是:

res.render("add_articles", {
title: "添加文章",
错误: 错误
});

您需要使用:

res.render("add_articles", {
title: "添加文章",
错误:errors.array()
});

来源:Express validator docs

关于javascript - 为什么我在 UI 中没有收到验证 Flash 消息,我收到这样的 Flash 错误 [object Object],[object Object],[object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545525/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com