我正在验证用户使用“emailcheck”输入的电子邮件,我在另一个问题上发现了一段代码,这是我的应用程序中的代码:
app.post("/blog", (req, res) => {
const name = req.body.name;
const email = req.body.email;
emailCheck(email).then(() => {
const newSubscriber = {name: name, email: email};
Subscriber.create(newSubscriber).then(() => {
res.redirect("/blog")
})
.catch((error) => {
res.json({serverErrorEmailExistence: "This email adress is already in use!"})
})
})
.catch(() => {
res.json({serverErrorEmailExistence: "This Email doesn't exist!"})
})
})
这是正常工作的,但是错误显示在一个新的空白页上。 我想在我的表格下显示错误。 表单是在我的应用程序中作为一个部分包含。
以下是HTML表单:
<section id="emailSub">
<div id="emailContainer">
<h1>Subscribe to my Newsletter</h1>
<p>You will get weekly emails when a post is published.</p>
<form action="blog" method="POST" id="emailForm" autocomplete="off">
<div class="field">
<input type="text" placeholder="Name: " name="name" required>
</div>
<div class="field">
<input type="email" placeholder="Email: " name="email" required>
</div>
<button type="submit">Subscribe!</button>
</form>
</div>
<div id="thankYouMsg">
<h1>Thank you for subscribing!</h1>
<p><i class="far fa-check-circle"></i></p>
</div>
<button id="exitForm"><i class="fas fa-times"></i></button>
</section>
我在博客主页上写到:
<%-include("partials/subscribe") %>
下面是我的订户模型:
const mongoose = require("mongoose");
const SubscriberSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
}
});
module.exports = mongoose.model("Subscriber", SubscriberSchema)
我怎样才能在表格中显示那个错误呢? ID为thankYouMSg的div在成功提交表单后显示,通常它是用CSS隐藏的。
我试着搜索这个,我找到了很多答案,但是我要么不知道如何将它们包含在我的代码中,要么我没有足够的理解来搜索正确的答案(可能两者都有)。 老实说,我只是把emailcheck代码包括在我的应用程序中,我所知道的最好的方法。 我真的不明白。catch(错误)在传递什么。
谢谢
所发生的情况是,如果出现错误,您将捕获该错误并返回一个json
-response,浏览器无法在html
中直接呈现该响应。
相反,您可以重新发送订阅页面,并将捕获到的错误消息传递到该页面,您可以在那里呈现该页面。 下面这样的内容应该可以帮助您开始:
在您的app.js中
...
.catch(() => {
res.render("your-subscribe-template.ejs", {
errorMessage: 'This Email doesn\'t exist!'
});
});
...
在您的模板中。ejs:
...
<% if (typeof errorMessage !== "undefined") { %>
<p>Form could not be submitted due to the following error:</p>
<p><%= errorMessage %></p>
<% } %>
...