【问题标题】:Getting Mailgun 'ERR_HTTP_HEADERS_SENT'获取 Mailgun 'ERR_HTTP_HEADERS_SENT'
【发布时间】:2023-03-14 21:26:01
【问题描述】:

我有一个返回状态和一些 JSON 的简单函数。 通过表单输入,我将用户数据保存到 Db 中,同时通过 mailgun 将电子邮件消息发送给该用户。一切正常,但终端可能会出现错误 这是它的代码。

exports.signup = (req, res) => {
  const errors = validationResult(req);

  if (!errors.isEmpty()) {
    return res.status(422).json({
      // error: [errors.array()[0].msg || errors.array()[1].msg],

      errors: [
        {
          msg: errors.array()[0].msg,
          param: errors.array()[0].param,
        },
      ],
    });
  }

  const user = new User(req.body);
  const { email, name } = req.body;
  user.save((err, user) => {
    if (err) {
      return res.status(400).json({
        err: "NOT able to save user in DB",
      });
    } else {
      res.json({
        name: user.name,
        email: user.email,
        id: user._id,
        // password: user.password,
      });
    }

    // mailgun - sending the mail
    const data = {
      from: "me@samples.mailgun.org",
      to: email,
      subject: "sending mail using mailgun",
      text: "Testing some Mailgun awesomness!",
      html: `<h1>Hey ${name} </h1> 
      <h2>Welcome , It's great to have you on board! </h2>`,
    };
    mg.messages().send(data, function (error, body) {
      // console.log("mail send to user successfully");
      if (error) {
        return res.json({
          error: error.message,
        });
      }
      res.json({ message: "Email has been send successfully" });
    });
  });
};

这会引发错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

_http_outgoing.js:526
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\express\lib\response.js:267:15)
    at Request.callback (C:\Users\Prathamesh\Desktop\College consession system\projBackend\controllers\auth.js:61:11)
    at IncomingMessage.<anonymous> (C:\Users\Prathamesh\Desktop\College consession system\projBackend\node_modules\mailgun-js\lib\request.js:331:19)
    at IncomingMessage.emit (events.js:323:22)
    at endReadableNT (_stream_readable.js:1204:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

【问题讨论】:

    标签: javascript reactjs express mongoose mailgun


    【解决方案1】:

    这是开发人员在向客户端发送响应时常犯的错误之一。

    这是一个实施错误。它与 Mailgun API 无关

    如果您仔细查看您的代码,在将用户数据写入数据库后,您正在发送响应

    res.json({
            name: user.name,
            email: user.email,
            id: user._id,
            // password: user.password,
          });
    

    同样,一旦发送了邮件,您就是在向客户端发送响应

    res.json({ message: "Email has been send successfully" });

    如果我是对的,这一定是问题所在。

    可能的解决方案可能是将您的代码更改为以下内容:

    exports.signup = async (req, res) => {
      const errors = validationResult(req);
    
      if (!errors.isEmpty()) {
        return res.status(422).json({
          // error: [errors.array()[0].msg || errors.array()[1].msg],
    
          errors: [
            {
              msg: errors.array()[0].msg,
              param: errors.array()[0].param,
            },
          ],
        });
      }
    
      const user = new User(req.body);
      const { email, name } = req.body;
      let userData = "null"
      
       try {
        userData = await user.save();
        } 
       catch(err){
         return res.json({
             error: err.message,
            });
         }
    
        // mailgun - sending the mail
        const data = {
          from: "me@samples.mailgun.org",
          to: email,
          subject: "sending mail using mailgun",
          text: "Testing some Mailgun awesomness!",
          html: `<h1>Hey ${name} </h1> 
          <h2>Welcome , It's great to have you on board! </h2>`,
        };
        mg.messages().send(data, function (error, body) {
          // console.log("mail send to user successfully");
          if (error) {
            return res.json({
              error: error.message,
            });
          }
          return res.json({ message: "Email has been send successfully",...userData });
        });
      });
    };
    
    

    【讨论】:

    • 感谢您回答我的问题,但我已经找到了解决方案……我删除了这行代码 res.json({ message: "Email has been send successfully" }); 。因为不需要我登录到控制台进行确认
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2021-11-04
    • 2020-03-25
    • 2020-05-26
    • 2021-07-15
    • 2022-01-26
    相关资源
    最近更新 更多