如何制作新闻通讯按钮

发布于 2025-01-13 00:22:04 字数 156 浏览 0 评论 0原文

需要一些有关反应网页中的新闻通讯按钮的快速指导。我想制作一个时事通讯按钮,用于接受用户的电子邮件并将其存储在电子表格中。基本上,我需要一些代码指导,以便当有人输入电子邮件并单击提交按钮时。他们将收到模板电子邮件,例如“感谢您订阅我们的时事通讯和公司电子邮件,我们会在电子表格中收到他们的电子邮件”。

Need some quick guidance regarding the newsletter button in react webpage. I wanna make a newsletter button that accepts, emails from users and stores them in a spreadsheet. Basically, I need some code guidance such that when someone enters their email and clicks submit button. They will get the template email like 'Thanks for subscribing to our newsletter and company email and we get their email in the spreadsheet.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁吢 2025-01-20 00:22:04

为了实现此功能,您的 React.js 前端将从用户那里获取电子邮件地址,并向包含该电子邮件地址的后端服务发送请求。
这可能看起来与此类似。

import { useState } from "react";
import "./styles.css";

function isValidEmailAddress(email) {
  // validate here
  return true;
}

export default function App() {
  const [address, setAddress] = useState("");

  async function subscribeNewsletter() {
    if (isValidEmailAddress(address)) {
      try {
        const response = await fetch("https://your-backend/subscription", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            email: address
          })
        });
        // check if request was successful (codes 200-299)
        // in this implementation we expect code "201 Created"
        if (!response.ok) {
          const parsed = JSON.parse(response.body);
          // show error message received from backend
          alert(parsed.msg);
        } else {
          alert("Subscribed.");
        }
      } catch (error) {
        alert("Subscription failed");
      }
    }
  }

  return (
    <div className="App">
      <input onChange={(e) => setAddress(e.target.value)} value={address} />
      <button onClick={() => subscribeNewsletter()}>Subscribe</button>
    </div>
  );
}

请参阅 CodeSandbox 了解最低限度的工作前端演示。

在后端中,您必须处理对 /subscription 端点的请求。在处理程序中,您可能会再次验证电子邮件地址,然后将其写入数据库或电子表格(如果您确实想使用我不推荐的电子表格)。
最后但并非最不重要的一点是,您需要发送欢迎电子邮件。最简单的方法是使用第 3 方 API,或者使用 SMTP JS 之类的东西来发送电子邮件。在这种情况下,您需要的是 SMTP 服务器。请查看此帖子了解更多详细信息。
后端服务可能看起来与此类似。

注意:这不是一个完美的实现,而是一个可以帮助您入门的框架。

import express from "express";

// create app
var app = express();
// middleware to parse json
app.use(express.json())

app.get('/', function (req, res) {
    // serve your react application
    res.sendFile("index.html");
});

app.post("/subscription", function (req, res) {
    const emailAddress = req.body.email;
    if (!isValidEmailAddress(emailAddress)) {
        // malformed email address
        res.status(400).send({
            msg: "email address is invalid"
        })
    }
    insertNewSubscriber(emailAddress);
    sendWelcomeEmail(emailAddress);
    // resource subsription has been created
    res.status(201).send();
});

// listen for request on port 3000
const port = 3000;
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

function isValidEmailAddress(email) {
    // validate here
    return true;
}

function insertNewSubscriber(email) {
    // write to database/ file/ spreadsheet etc.
}

function sendWelcomeEmail(email) {
    // send email e.g. using 3rd party API
}

In order for this to work you would have your React.js frontend that would get the e-mail address from the user and send a request to your backend service containing that e-mail address.
This could look similar to this.

import { useState } from "react";
import "./styles.css";

function isValidEmailAddress(email) {
  // validate here
  return true;
}

export default function App() {
  const [address, setAddress] = useState("");

  async function subscribeNewsletter() {
    if (isValidEmailAddress(address)) {
      try {
        const response = await fetch("https://your-backend/subscription", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            email: address
          })
        });
        // check if request was successful (codes 200-299)
        // in this implementation we expect code "201 Created"
        if (!response.ok) {
          const parsed = JSON.parse(response.body);
          // show error message received from backend
          alert(parsed.msg);
        } else {
          alert("Subscribed.");
        }
      } catch (error) {
        alert("Subscription failed");
      }
    }
  }

  return (
    <div className="App">
      <input onChange={(e) => setAddress(e.target.value)} value={address} />
      <button onClick={() => subscribeNewsletter()}>Subscribe</button>
    </div>
  );
}

See CodeSandbox for a minimal working demo of the frontend.

Within your backend you have to handle the request to the /subscription endpoint. In a handler you will probably validate the email address again and then write it into a database or spreadsheet (if you really want to use spreadsheets which I would not recommend).
Last but not least you need to send the welcome email. The easiest way to do this is to use a 3rd party API or you use something like SMTP JS to send an email. What you will need in that case is a SMTP server. Have a look on this thread for more details.
The backend service could then look similar to this.

Note: this is not a perfect implementation but a skeleton that should help you getting started.

import express from "express";

// create app
var app = express();
// middleware to parse json
app.use(express.json())

app.get('/', function (req, res) {
    // serve your react application
    res.sendFile("index.html");
});

app.post("/subscription", function (req, res) {
    const emailAddress = req.body.email;
    if (!isValidEmailAddress(emailAddress)) {
        // malformed email address
        res.status(400).send({
            msg: "email address is invalid"
        })
    }
    insertNewSubscriber(emailAddress);
    sendWelcomeEmail(emailAddress);
    // resource subsription has been created
    res.status(201).send();
});

// listen for request on port 3000
const port = 3000;
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

function isValidEmailAddress(email) {
    // validate here
    return true;
}

function insertNewSubscriber(email) {
    // write to database/ file/ spreadsheet etc.
}

function sendWelcomeEmail(email) {
    // send email e.g. using 3rd party API
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文