You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React电商网站:如何将表单用户邮箱传入Nodemailer的mailOptions

解决表单邮箱传入Nodemailer的问题

核心问题分析

你当前的问题出在请求方法不匹配和缺少表单数据解析中间件:

  • 表单默认用GET提交,数据会挂在URL的query参数里,但你服务端用req.body去取值,自然拿不到;
  • 就算改成POST,Express默认也不会解析表单格式的请求体,必须加中间件处理。

第一步:修改服务端代码

  1. 先添加表单数据解析中间件(要放在路由定义之前):
// 放在app.get('/submit')之前
app.use(express.urlencoded({ extended: true }));

这个中间件会把表单提交的x-www-form-urlencoded格式数据解析到req.body中,让你能直接拿到用户输入的邮箱。

  1. 把GET路由改成POST路由(POST更适合表单提交,还能避免邮箱暴露在URL里):
// 将app.get替换为app.post
app.post('/submit', (req, res) => {  
    // 提取用户邮箱,先做简单校验
    const userEmail = req.body.userEmail;
    if (!userEmail) {
        return res.status(400).send('请填写有效邮箱');
    }

    let mailOptions = {
        from: process.env.DB_EMAIL,
        to: userEmail, // 直接使用获取到的用户邮箱
        subject:"Welcome to SkyeSkates",
        text: "Whoop Whoop! You are officially part of the team!"
    }
    transporter.sendMail(mailOptions, (err, success)=>{
        if(err){
            console.log(err);
            return res.status(500).send('订阅邮件发送失败');
        }else{
            console.log("email sent!");
            res.send('订阅成功!');
        }
    })
}) 

第二步:修改客户端表单代码

给表单加上method="POST"属性,明确用POST方法提交数据:

<form action="/submit" method="POST" class="contact-form">
    <h1>Pssst, hey, you <br/> (yeah, you)</h1>
    <p>Want in on new arrivals, exclusive collabs, sales and more? <br/> Well, you know what to do.</p>
    <input type="email" name="userEmail" id="userEmail" placeholder='Your email, please' required></input>
    <input type="submit" id="send-btn" value="Send Message"></input>
    <br/>
    <small>To see how we may use your information, take a look at our privacy policiy.</small>        
</form> 

额外建议:把输入框的type="text"改成type="email",浏览器会自动做邮箱格式校验;再加required属性强制用户填写邮箱。


测试验证

重启服务端,在客户端填写邮箱提交,服务端控制台应该能打印"email sent!",用户也能收到订阅邮件。如果仍有问题,检查:

  • 环境变量DB_EMAIL和DB_PASS是否配置正确;
  • Gmail是否开启了App Password(比低安全性应用权限更安全)。

内容的提问来源于stack exchange,提问作者Alexa Pettitt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:30:51