ReferenceError: data is not defined in nodemailer.sendMail()

问题描述 投票:0回答:1

我正在使用 Node.js v18.15.0 和 nodemailer 在我的电子商务应用程序中发送电子邮件。但是,我的 emailCtrl.js 文件中出现“ReferenceError: data is not defined”错误。具体来说,错误发生在 sendMail() 函数中,我正在尝试使用“收件人”字段设置收件人电子邮件地址。

这里是我的emailCtrl.js文件中的相关代码:

// send mail with defined transport object
let info = await transporter.sendMail({
  from: '"hey" <[email protected]>',
  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);
  }
});

我试图通过确保定义了“数据”对象来修复错误,但我仍然收到错误。

有人可以帮我找出导致此错误的原因以及解决方法吗?

环境相关信息:

Node.js v18.15.0 节点邮件

node.js nodemailer
1个回答
0
投票

这似乎与范围有些混淆,您在

data
内的闭包范围内定义了
asyncHandler
但是您尝试在
data
的参数中使用的
let info = await transporter.sendMail
对象确实未定义。

// 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" <[email protected]>',
  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
});

© www.soinside.com 2019 - 2024. All rights reserved.