NodeJS 错误:在将标头发送到客户端后无法设置标头:节点邮件器

bvhaajcl  于 2023-01-12  发布在  Node.js
关注(0)|答案(2)|浏览(176)

我正在使用nodemailer发送电子邮件给用户,但当我点击API时,我得到这个错误:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client我不明白为什么这是路线代码:

exports.create = async (req, res) => { 

    // Check if the attendee already exists
    let user = await Attendee.findOne({ email: req.body.email });
    if (user) {
      return res
        .status(400)
        .json({ error: "An attendee with this email already exists" });
    }

    // sending verification link to the user
    const mailData = {
      from: process.env.USER_ID,
      
      to: req.body.email,
      
      subject: "Email Verification link",
      text: `Click on the link and verify your email`,
      // verification link 
      html: `<a href="localhost:8000/api/verify">Click here to verify</a>`,
    };

    // sending the email
    transporter.sendMail(mailData, (error, info) => {
      if (error) console.log(error);
      console.log("Email Sent Successfully");
      
    });
    res.send(200).json({message:"Verification link has been sent to your email. Please verify your email"})

    
  };

有人能告诉我为什么会发生这种情况吗?我该如何解决这个问题

92dk7w1h

92dk7w1h1#

这是因为你同时使用了异步和回调函数。因为回调函数和异步函数并行执行,所以导致了这个问题。
最好的方法做较少的变化,如下所示,放在else条件。

exports.create = async (req, res) => { 

    // Check if the attendee already exists
    let user = await Attendee.findOne({ email: req.body.email });
    if (user) {
      return res
        .status(400)
        .json({ error: "An attendee with this email already exists" });
    }else {

        // sending verification link to the user
        const mailData = {
          from: process.env.USER_ID,
          
          to: req.body.email,
          
          subject: "Email Verification link",
          text: `Click on the link and verify your email`,
          // verification link 
          html: `<a href="localhost:8000/api/verify">Click here to verify</a>`,
        };
    
        // sending the email
        transporter.sendMail(mailData, (error, info) => {
          if (error) console.log(error);
          console.log("Email Sent Successfully");
          
        });
        res.status(200).json({message:"Verification link has been sent to your email. Please verify your email"})
    }
    
};
ccgok5k5

ccgok5k52#

res.send(STATUS_CODE).json()

已弃用。有关详细信息,请参阅此处。
请改为使用以下命令:

res.status(200).json({message:"Verification link has been sent to your email. Please verify your email"}})

(Also见此)

相关问题