如何在ejs中显示express错误

How to display express errors in ejs

我正在验证用户使用 "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!"})
    })

但是,我得到了 "cannot look up view /blog in views"。我试过同样的 res.redirect 它只是加载而没有发生任何事情。

发生的事情是,如果出现错误,您会捕获此错误并且 return 浏览器无法直接在 html 中呈现的 json 响应。

您可以做的是重新发送您的订阅页面并将捕获的错误消息传递到该页面,您可以在那里呈现该页面。像这样的东西应该可以帮助你开始:

在你的app.js

...
.catch(() => {
    res.render("your-subscribe-template.ejs", {
        errorMessage: 'This Email doesn\'t exist!'
    });
});
...

在你的 template.ejs:

...
<% if (typeof errorMessage !== "undefined") { %>
    <p>Form could not be submitted due to the following error:</p>
    <p><%= errorMessage %></p>
<% } %>
...