Node mailer Error: can't set headers after they are sent

Node mailer Error: can't set headers after they are sent

我已经尝试在创建新资源后发送邮件,并且在创建新用户之前它应该检查电子邮件和员工编号是否有任何相同的值它应该显示已经存在或者它会添加新资源并有发送邮件。

如果email和emp no不一样,完美创建资源和发送邮件。但如果我尝试使用相同的邮件或 emp 号码,我会收到错误

我的错误:

events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:489:11)
    at ServerResponse.setHeader (_http_outgoing.js:496:3)
    at ServerResponse.header (D:\hourmint\node_modules\express\lib\response.js:7
30:10)
    at ServerResponse.location (D:\hourmint\node_modules\express\lib\response.js
:847:15)
    at ServerResponse.redirect (D:\hourmint\node_modules\express\lib\response.js
:885:18)
    at D:\hourmint\app\routes.js:298:18
    at D:\hourmint\node_modules\mongoose\lib\query.js:2917:18
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

我的发射器:

var smtpTransport = nodemailer.createTransport({
  service: 'Gmail',
  auth: {
    user: 'noemail@gmail.com',
    pass: 'mypassword'
  },
});

我的代码:

app.post('/addresources', isLoggedIn, function(req, res) {
  var id = (req.body._id) ? req.body._id : mongoose.Types.ObjectId(0);
  var newPwd = new mongo.resource();

  var pwd = newPwd.generateHash(req.body.res_password);
  var resourceValue = {
    'role_id': req.body.role_id,
    'privilege_id': req.body.privilege_id,
    'res_fname': req.body.res_fname,
    'res_lname': req.body.res_lname,
    'res_email': req.body.res_email,
    'res_password': pwd,
    'res_empno': req.body.res_empno,
    'res_city': req.body.res_city,
    'res_mobile': req.body.res_mobile,
    'res_emerno': req.body.res_emerno,
    'res_hourlyrate': req.body.res_hourlyrate,
    'res_otp': 0,
    'res_status': req.body.res_status
  };

  mongo.resource.findOne({
    $or: [{
      'res_email': req.body.res_email
    }, {
      'res_empno': req.body.res_empno
    }]
  }).exec(function(err, user) {
    if (err) throw err;
    if (user) {
      console.log(user)
      if (user.res_email == req.body.res_email && user.res_empno == req.body.res_empno) {

        req.flash('error', 'Email And Employee Number Already Exists!!!')
        res.redirect('/resources')


      } //user already exists with email AND/OR phone.
      else if (user.res_email == req.body.res_email) {

        req.flash('error', 'Email Id  Already Exists!!!')
        res.redirect('/resources')


      } //no users with that email NOR phone exist.
      else(user.res_empno == req.body.res_empno) {

        req.flash('error', 'Employee Number Already Exists!!!')
        res.redirect('/resources')

      }
    } else {


      mongo.resource.findOneAndUpdate({
        '_id': id
      }, resourceValue, {
        upsert: true,
        new: true
      }, function(err, response) {
        if (err) throw err;


        console.log("Resource Added SuccessFully")
        console.log(response.res_email)
        res.redirect('/resources')

        var mainOptions = {
          from: '"Niyati" <noemail@gmail.com>',
          to: response.res_email,
          subject: 'Hello ✔', // Subject line
          text: 'Hello world ?', // plaintext body
          html: '<b>Hello world ?</b>' // html body
        };
        //console.log("html data ======================>", mainOptions.html);
        smtpTransport.sendMail(mainOptions, function(err, info) {
          if (err) throw err;
          console.log("mail Sent");
          // console.log(err);
        });

      });
    }
  });
});

问题是由您的 if else 条件中的缺陷引起的。当第一个 if 匹配时

user.res_email == req.body.res_email && user.res_empno == req.body.res_empno 

else if 语句也将匹配。所以 res.redirect 被触发了两次。

请优化您的 if/else 条件以确保没有重叠。