【发布时间】:2020-10-01 04:47:00
【问题描述】:
我正在验证用户使用“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(error) 传递的是什么。
谢谢
按照我试过的答案:
.catch(() => {
res.render("/blog", {errorMessage: "This email adress is already in use!"});
})
})
.catch(() => {
res.render("/blog", {errorMessage: "This Email doesn't exist!"})
})
但是,我得到“无法在视图中查找视图/博客”。我也试过了 res.redirect,它只是加载而没有任何事情发生。
【问题讨论】:
标签: node.js mongodb express error-handling ejs