Node.js 使用 Nodemailer 发送邮箱验证码并解决 userinfo.username 为 undefined 的问题
Node.js 使用 Nodemailer 发送邮箱验证码并解决 userinfo.username 为 undefined 的问题
// 插入用户邮箱和验证码
const sqlStr2 = `update userinfo set email=?,ecode=? where username=? ;`;
db.query(sqlStr2, [userinfo.email, code, userinfo.username], (err, results) => {
if (err) {
return res.cc(err);
}
if (results.affectedRows !== 1) {
console.log(userinfo.email,code,userinfo.username);
return res.cc('邮箱插入失败!请稍后再试!');
}
// 发送邮箱验证码
let transporter = nodemailer.createTransport({
host: 'smtp.163.com',
port: 465, // SMTP 端口
auth: { //发送者的账户和授权码
user: '15576730892@163.com', //账户
pass: 'LRTYRUNEMKHWLVZS', //smtp授权码,到邮箱设置下获取
}
});
let mailOptions = {
from: '15576730892@163.com', // 发送者昵称和地址
to: userinfo.email, // 接收者的邮箱地址
subject: '验证码', // 邮件主题
html: code + '\n次元人欢迎您的到来!'
};
//发送邮件
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('邮件发送成功 ID:', info.messageId);
res.write('邮件发送成功 ID:', info.messageId);
res.end();
});
res.cc('验证码发送成功!', 0);
})
userinfo.username 输出 undefined 的原因
userinfo.username 输出 undefined 的原因可能有以下几种可能性:
- 在请求中没有正确传递 username 参数,导致 userinfo 对象中的 username 属性值为 undefined。
- 在数据库中没有找到与传递的 username 匹配的记录,导致 userinfo 对象中的 username 属性值为 undefined。
- userinfo 对象中的 username 属性本身就是 undefined。
解决方法
- 检查请求参数是否正确传递 username,并确保其值不为 undefined。
- 检查数据库中是否确实存在与传递的 username 匹配的记录。
- 检查 userinfo 对象的定义,确保 username 属性已正确赋值。
代码优化
为了提高代码可读性和维护性,可以对代码进行以下优化:
- 使用 async/await 简化代码,避免回调函数嵌套。
- 使用 try/catch 处理异常,提高代码健壮性。
- 使用环境变量存储敏感信息,例如邮箱地址和授权码,避免硬编码。
总结
本文介绍了如何使用 Node.js 的 Nodemailer 库发送邮箱验证码,并分析了 userinfo.username 为 undefined 的原因及解决方法。希望本文能帮助您解决类似的问题。
原文地址: https://www.cveoy.top/t/topic/qhL9 著作权归作者所有。请勿转载和采集!