参考错误:data在nodemailer中没有定义,sendMail()

zy1mlcev  于 2023-04-29  发布在  Node.js
关注(0)|答案(1)|浏览(168)

我在使用Node。js v18.15.0和nodemailer在我的电子商务应用程序中发送电子邮件。但是,我得到了一个“ReferenceError:我的电子邮件中存在“数据未定义”错误Ctrl。js文件。具体来说,错误发生在sendMail()函数中,我试图使用“to”字段设置收件人电子邮件地址。
下面是我的emailCtrl中的相关代码。js文件:

// send mail with defined transport object
let info = await transporter.sendMail({
  from: '"hey" <abc@gmail.com>',
  to: data.to, // Error occurs here
  subject: data.subject,
  text: data.text,
  html: data.html,
 });

// Generate Password Token
const forgotPasswordToken = asyncHandler(async (req, res) => {
  const { email } = req.body;
  const user = await User.findOne({ email });
  if (!user) throw new Error("User not found with this Email");
  try {
    const token = await user.createPasswordResetToken();
    await user.save();
    const resetURL = `Hi Please follow this link to reset your 
Password. This link is valid for 10 minutes from now. <a 
href="http://localhost:5000/api/user/reset- 
password/${token}">Click Here</a>`;

    const data = {
      to: email,
      subject: "Reset Password Link",
      text: "Hey user",
      html: resetURL, // fixed the typo here
    };
    console.log(data);
    sendEmail(data);
    res.json(token);
  } catch (error) {
    throw new Error(error);
  }
});

我已经尝试通过确保定义了“data”对象来修复错误,但我仍然收到错误。
有人能帮我弄清楚是什么原因导致了这个错误,以及如何修复它?
环境相关信息:
Node.js v18.15.0节点邮件

avwztpqn

avwztpqn1#

这似乎是一些与作用域的混淆,你在asyncHandler中定义了data,但是你试图在let info = await transporter.sendMail的参数中使用的data对象确实是未定义的。

// The reachable scope for the object passed as argument in sendEmail is here, 
// So this would be the right place to define it :
/*
const data = {
  to: "...",
  subject: "...",
  text: "...",
  html: "..."
};

// and then
let info = await transporter.sendMail({
  from: '...',
  ...data, // (use the rest operator to copy the fields of the object and you won't have to copy manually each one of them)
});
*/

let info = await transporter.sendMail({
  from: '"hey" <abc@gmail.com>',
  to: data.to, // This data is not defined in that scope in your code
  subject: data.subject,
  text: data.text,
  html: data.html,
});

const forgotPasswordToken = asyncHandler(async (req, res) => {
  // ...
  // The object data defined here is only reachable in the scope of that closure
  const data = {
    to: email,
    subject: "Reset Password Link",
    text: "Hey user",
    html: resetURL,
  };

  sendEmail(data);
  // ...
  // and it goes out of scope here
});

相关问题