时事通讯注册 api 的问题

问题描述

我创建的表单旨在将用户输入的电子邮件发送到我的 Sendgrid 联系人列表。它成功地做到了这一点,但有几个问题:

  1. 提交时页面一直在加载

  2. 前端逻辑不起作用,因为我希望它隐藏输入和显示文本

这是后端代码

app.post('/subscribe',(req,res) => {
    const { email } = req.body;
    const options = {
        method: 'PUT',url: 'https://api.sendgrid.com/v3/marketing/contacts',headers:
        {
            'content-type': 'application/json',authorization: 'Bearer **MYSECRETKEY**'
        },body:
        {
            list_ids: ['**MYSECRETID**'],contacts:
                [{
                    email: email,}]
        },json: true
    };

    request(options,function (error,response,body) {
        if (error) { 
            throw new Error(error);
        } else {
            res.status(200);
        }
    });
})

这是表格

<div id="signup">
                <form action="/subscribe" method="POST" novalidate class="validated-form">
                    <label class="form-label" for="signup">Signup to receive the latest tips & trends</label>
                    <input class="form-control" type="email" id="email" name="email" placeholder="youremail@email.com" required>
                    <input type="submit" value="SUBMIT" class="button" id="cta">
                </form>
            </div>
            <div id="success" class="inner-form">
                <h2 class="text-center">Thank you!</h2>
            </div>

这里是前端 Javascript

<script>

    let cta = document.getElementById('cta');
    let email = document.getElementById('email').value;
    let error = document.getElementById('error');
    let success = document.getElementById('success');
    let signup = document.getElementById('signup');

    cta.addEventListener('click',(event) => {

        if (this.email.value == null || this.email.value == "") {
            error.classList.add('errorAnim');
        } else {
            let fetchData = {
                method: 'POST',body: JSON.stringify({ email: this.email.value }),headers: { "Content-Type": "application/json" }
            }

            fetch('/subscribe',fetchData)
                .then(res => {
                    if (res.ok) {
                        signup.classList.add('fadeout');
                        success.classList.add('fadein');
                    } else {
                        error.classList.add('errorAnim');
                    }
                })
        }
    })

    (function () {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.validated-form')

    // Loop over them and prevent submission
    Array.from(forms)
        .forEach(function (form) {
            form.addEventListener('submit',function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
                }

                form.classList.add('was-validated')
            },false)
        })
})()

</script>

非常感谢您的帮助!我还在学习中

解决方法

这里是 Twilio SendGrid 开发者布道者。

如果您的服务器端加载卡住,则可能是 API 返回错误,而您没有响应请求。尝试在错误子句中添加响应:

    request(options,function (error,response,body) {
        if (error) { 
            throw new Error(error);
            res.status(500).send(error.message);
        } else {
            res.status(200).send();
        }
    });

在您的前端代码中,您引用了 this.email,但我不认为 this.email 是在此上下文中设置的。您之前确实创建了一个 email 变量 (let email = document.getElementById('email').value;),但这是代码在页面加载时运行时电子邮件字段的值,而不是在提交表单时。因此,我会更改变量以仅获取元素,然后使用 email 变量在发送时查找值。

最好是监听表单的提交事件,而不是表单中按钮的点击事件。这允许您通过在表单字段中按回车来捕获表单提交,而不是仅仅依靠单击按钮。然后,当您执行此操作时,您需要阻止默认的表单提交行为。您可以使用 event.preventDefault() 执行此操作。

让我们更新 HTML 以在表单中添加一个 id,以便我们稍后选择它:

<div id="signup">
  <form action="/subscribe" method="POST" novalidate class="validated-form" id="signup-form">
    <label class="form-label" for="signup">Signup to receive the latest tips & trends</label>
    <input class="form-control" type="email" id="email" name="email" placeholder="youremail@email.com" required>
    <input type="submit" value="SUBMIT" class="button" id="cta">
  </form>
</div>
<div id="success" class="inner-form">
  <h2 class="text-center">Thank you!</h2>
</div>
    let form = document.getElementById('signup-form');
    let email = document.getElementById('email');
    let error = document.getElementById('error');
    let success = document.getElementById('success');
    let signup = document.getElementById('signup');

    form.addEventListener('submit',(event) => {
        event.preventDefault();
        if (email.value == null || email.value == "") {
            error.classList.add('errorAnim');
        } else {
            let fetchData = {
                method: 'POST',body: JSON.stringify({ email: email.value }),headers: { "Content-Type": "application/json" }
            }

            fetch('/subscribe',fetchData)
                .then(res => {
                    if (res.ok) {
                        signup.classList.add('fadeout');
                        success.classList.add('fadein');
                    } else {
                        error.classList.add('errorAnim');
                    }
                })
        }
    })

让我知道这些是否有帮助。