获取 Mailgun 'ERR_HTTP_HEADERS_SENT'

Getting Mailgun 'ERR_HTTP_HEADERS_SENT'

我有一个简单的函数,returns 一个状态和一些 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...

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

这是一个实现错误。它与 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 });
    });
  });
};