使用Nodemailer从表单发邮件出现收件人未定义错误求助
问题解决:表单提交邮箱字段未被服务端识别,Nodemailer提示无收件人
核心问题分析
- 服务端语法错误:
mailOptions中from字段后缺少逗号,导致JS语法错误,直接中断邮件发送逻辑 - 请求格式不匹配:客户端用
FormData发送multipart/form-data格式请求,但服务端仅配置了bodyParser.urlencoded,无法解析该格式,导致req.body无法正确获取邮箱字段 - 重复绑定事件风险:表单提交事件绑定在
goFlower4函数内,若函数多次执行会重复绑定事件,可能引发多次请求或异常行为
分步解决方案
1. 修复服务端语法错误
打开app.js,在mailOptions的from字段后添加逗号:
// Email content const mailOptions = { from: 'myemail@gmail.com', // 新增逗号修复语法错误 to: email, subject: 'Happy Birthday!', text: "Your days have grown weary and your purpose on this planet is unclear. At 33, the time has come. Click here to reveal all the answers you've been waiting for." };
2. 调整服务端解析中间件以支持FormData
安装multer中间件用于解析multipart/form-data格式:
npm install multer
在app.js中引入并配置:
const express = require('express'); const nodemailer = require('nodemailer'); const bodyParser = require('body-parser'); const cors = require('cors'); const multer = require('multer'); // 新增 const upload = multer(); // 新增,无磁盘存储配置 const app = express(); const port = 3000; app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.none()); // 新增,解析非文件类型的FormData字段 // Allow requests from a specific origin app.use(cors({ origin: 'http://127.0.0.1:5500' })); // 其余代码保持不变
3. 避免重复绑定表单提交事件
将submit事件绑定移到goFlower4函数外,确保仅绑定一次:
// 页面加载时绑定一次提交事件 form.addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(this); fetch('http://localhost:3000/send-email', { method: 'POST', body: formData }) .then(response => response.text()) .then(data => { console.log(data); if (data === 'Email sent successfully') { console.log('Email sent successfully'); } else { console.error('Error: Something went wrong'); } }) .catch(error => { console.error('Error:', error); }); }); function goFlower4() { update(locations[2]); for (let button of responseButtons) { button.style.display = "none"; } form.style.display = 'inline-block'; }
4. 清理HTML表单冗余属性
移除form标签上空的name属性,避免潜在干扰:
<form id="form" action="/send-email" method="post"> <label for="email">My email address is </label> <input type="email" id="email" name="email" autocomplete="on" required> <button type="submit" id="submit">send</button> </form>
验证步骤
- 重启Node.js服务
- 测试表单提交,查看浏览器网络面板确认
email字段正确发送 - 检查服务端控制台,确认
Recipient Email输出正确的邮箱地址 - 验证邮件是否成功发送
内容的提问来源于stack exchange,提问作者Passionfruit92
相关产品推荐
相关产品推荐

