错误:无法在将响应头发送给客户端后设置响应头:Nodemailer

huangapple go评论72阅读模式
英文:

Error Cannot set headers after they are sent to the client : Nodemailer

问题

我正在使用nodemailer向用户发送电子邮件,但当我调用API时出现以下错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我不明白为什么会出现这个错误
这是路由代码:

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

    // 检查参会者是否已存在
    let user = await Attendee.findOne({ email: req.body.email });
    if (user) {
      return res
        .status(400)
        .json({ error: "该邮箱已经存在的参会者" });
    }

    // 向用户发送验证链接
    const mailData = {
      from: process.env.USER_ID,
      to: req.body.email,
      subject: "电子邮件验证链接",
      text: `点击链接验证您的电子邮件`,
      // 验证链接
      html: `<a href="localhost:8000/api/verify">点击这里验证</a>`,
    };

    // 发送电子邮件
    transporter.sendMail(mailData, (error, info) => {
      if (error) console.log(error);
      console.log("电子邮件发送成功");
    });
    res.send(200).json({message: "验证链接已发送到您的电子邮件,请验证您的电子邮件"})
  };

有人可以告诉我为什么会发生这种情况以及如何解决吗?

英文:

I am using nodemailer to send email to the user but when I hit the api i get this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I can't understand why
This is the route code:

exports.create = async (req, res) =&gt; { 


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

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

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

    
  };

Can anyone tell me why this is happening and how do I fix this

答案1

得分: 1

这是由于您同时使用了异步和回调函数导致的。
由于回调函数与异步同时执行,所以会导致这个问题。

以最少的更改方式来处理,将以下内容放在else条件中。

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

    // 检查参会者是否已存在
    let user = await Attendee.findOne({ email: req.body.email });
    if (user) {
        return res
            .status(400)
            .json({ error: "此电子邮件的参会者已存在" });
    } else {

        // 发送验证链接给用户
        const mailData = {
            from: process.env.USER_ID,
            to: req.body.email,
            subject: "电子邮件验证链接",
            text: "点击链接并验证您的电子邮件",
            // 验证链接
            html: `<a href="localhost:8000/api/verify">点击此处进行验证</a>`,
        };

        // 发送电子邮件
        transporter.sendMail(mailData, (error, info) => {
            if (error) console.log(error);
            console.log("电子邮件发送成功");
        });
        res.status(200).json({ message: "验证链接已发送至您的电子邮件,请验证您的电子邮件" })
    }
};
英文:

That's due to you used async and callback function together.
As callback performs in parallel excution with async so it cause this issue.

Best way to do with less changes as below put inside else condition.

exports.create = async (req, res) =&gt; { 


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

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

答案2

得分: 0

res.send(STATUS_CODE).json()

已被弃用。请查看此处获取更多信息。

而应使用以下方式:

res.status(200).json({ message: "已发送验证链接到您的电子邮件,请验证您的电子邮件" })

(还请查看此处)


<details>
<summary>英文:</summary>

```js
res.send(STATUS_CODE).json()

is deprecated. See here for more information.

Instead, use the following:

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

(Also see this)

huangapple
  • 本文由 发表于 2023年1月10日 11:47:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75065270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定