我正在开发一个允许用户在页面上发布消息的Web应用程序。我有两个ejs文件:
index.ejs,具有供用户放置信息并呈现数据库中用户名和消息的完整列表的表单。
validation.ejs可以帮助我显示带有aJax的错误消息(因为我不希望出现错误时刷新页面,结果我的列表会消失),并且我正在使用猫鼬为了存储数据,所有输入要求都以猫鼬设置。
当我提交一个空白表格时,我收到错误消息,显示(“名称不能为空”,“消息不能为空”),但是当我再次提交所提供的信息时,它仍然显示错误,我的问题是:是否有一种方法可以在ajax中使用“如果不是”条件,该条件可以显示错误或成功添加用户?
server.js:
var express = require("express");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
const flash = require("express-flash");
const session = require("express-session");
mongoose.connect(
"mongodb://localhost/messageDashboard",
{ useNewUrlParser: true },
);
const CommentSchema = new mongoose.Schema(
{
commenter: {
type: String,
required: [true, "Commenter cannot be empty"],
},
comment: {
type: String,
required: [true, "Comment cannot be empty"],
},
},
{ timestamps: true },
);
const MessageSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Name cannot be empty"],
},
message: {
type: String,
required: [true, "Message cannot be empty"],
},
comments: [CommentSchema],
},
{ timestamps: true },
);
const Message = mongoose.model("Message", MessageSchema);
var app = express();
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(flash());
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 },
}),
);
app.get("/", function(req, res) {
Message.find({}, function(err, messages) {
if (err) {
res.redirect("/");
} else {
console.log(messages);
res.render("index", { messages: messages });
}
});
});
app.post("/postMessage", function(req, res) {
var newMessage = new Message(req.body);
newMessage.save(function(err) {
if (err) {
console.log("there is a error when posting", err.errors);
for (var e in err.errors) {
req.flash("postMsg", err.errors[e].message);
}
res.render("validation", { errors: newMessage.errors });
} else {
console.log("success added a user");
res.redirect("/");
}
});
});
app.listen(8000, function() {
console.log("listening on port 8000");
});
index.ejs:
<body>
<h2>Welcome to Message Board </h2>
<div id='placeholder'>Placeholder</div>
<form action='/postMessage' method='post' class='postForm'>
<h4>Name:</h4>
<input type='text' name='name'>
<h4>Message:</h4>
<input type='text' style="width: 600px; height: 100px;" name='message'><br>
<button id='submitMessage' style='margin-left: 520px; background-color: darkorange;' type='submit'>Post Message</button>
</form>
<script>
$('.postForm').submit(function(e){
e.preventDefault()
$.ajax({
url: '/postMessage',
method: 'POST',
data: $(this).parent().serialize(),
success: function(serverResponse){
console.log('ajax is working')
$('#placeholder').html(serverResponse)
}
})
})
</script>
validation.ejs:
<body>
<% if(messages.postMsg){ %>
<% for(var x of messages.postMsg) {%>
<h5 style='color: crimson'><%= x %></h5>
<% } %>
<% } %>
</body>
答案 0 :(得分:0)
您应该做两件事:
400
,Bad Request
)从API返回错误响应。