Expressjs错误:Headers ServerResponse.OutgoingMessage.setHeader

时间:2017-11-13 20:19:58

标签: node.js express

在我的注册用户帐户Express 4应用程序中,我收到此错误:

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)

仅在尝试使用现有电子邮件注册时才会出现错误,然后是现有用户名。 (我按预期得到了flash消息。)

使用独特的电子邮件和独特的用户名进行注册非常有效。

我了解到错误可能是: *当人们将快速路由中的异步响应视为同步响应并且最终发送数据两次时,通常会发生错误。*

我没有看到我两次发送"数据的位置"

感谢您的帮助 - Rob

  

CODE

/**
 * GET /signup
 * Signup page.
 */
exports.getSignup = (req, res) => {
  if (req.user) {
    return res.redirect('/account');
  }
  res.render('account/signup', {
    title: 'Create Account'
  });
};

/**
 * POST /signup
 * Create a new local account.
 */

exports.postSignup = (req, res, next) => {
  req.assert('email', 'Email is not valid').isEmail();
  req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6);
  req.sanitize('email').normalizeEmail({
    gmail_remove_dots: false
  });

  const errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/signup');
  }

  const user = new User({
    email: req.body.email,
    username: req.body.username,
    // password: req.body.password
  });

  User.findOne({
    email: req.body.email
  }, (err, existingUser) => {
    if (err) {
      return next(err);
    }
    if (existingUser) {
      req.flash('errors', {
        msg: 'Account with that email address already exists.'
      });
      return res.redirect('/signup');
    }
  });

  User.findOne({
    username: req.body.username
  }, (err, existingUser) => {
    if (err) {
      return next(err);
    }
    if (existingUser) {
      req.flash('errors', {
        msg: 'Account with that username name already exists.'
      });
      return res.redirect('/signup');
    }

  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    req.logIn(user, (err) => {
      if (err) {
        return next(err);
      }
      // doesn't wokr either res.redirect('/account');
      return res.redirect('/account');
    });
  });
};

**注意** - 我的代码开头 - https://github.com/sahat/hackathon-starter/blob/731ec259c3d17fbee8171f2d280cbdf283177b76/controllers/user.js - 我将用户名添加到注册表单

1 个答案:

答案 0 :(得分:0)

我在findOne语句中使用$或:工作。 (我的要点,“嵌套”解决方案似乎并不总是有效)

User.findOne({$or: [
      {email: req.body.email},
      {username: req.body.username}
      ]
      }).exec(function(err, existingUser){

但我想知道我是否应该使用此解决方案的承诺?

此处为完整代码。

/**
 * POST /signup
 * Create a new local account.
 */


exports.postSignup = (req, res, next) => {
  req.assert('email', 'Email is not valid').isEmail();
  req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6);
  req.sanitize('email').normalizeEmail({
    gmail_remove_dots: false
  });

  const errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/signup');
  }

  const user = new User({
    email: req.body.email,
    username: req.body.username,
    // password: req.body.password
  });

  User.findOne({$or: [
      {email: req.body.email},
      {username: req.body.username}
      ]
      }).exec(function(err, existingUser){

    // console.log('existingUser.email ' + existingUser.email)
    // console.log('existingUser.email ' + existingUser.username)

    if (!existingUser){
      console.log('now existing user was found');
      console.log('no users with that email NOR phone exist');
      user.save((err) => {
        if (err) { return next(err); }
        req.logIn(user, (err) => {
          if (err) {
            return next(err);
          }
          res.redirect('/account');
        });
      });
    } else if (existingUser.email == req.body.email) {
        console.log('user already exists with EMAIL ');
        req.flash('errors', { msg: 'Account with that EMAIL  already exists.' });
        return res.redirect('/signup');
      }
      else if (existingUser.username = req.body.username){
        console.log('user already exists with USERNAME.');
        req.flash('errors', { msg: 'Account with that USERNAME  already exists.' });
        return res.redirect('/signup');

      }
      else {
      // nothing
        return res.redirect('/signup');
      }

  });

}; // END exports.postSignup {}