即使在返回声明之后,代码仍在执行?

时间:2018-01-21 09:03:59

标签: javascript node.js mongodb express

我正在使用mongoose唯一验证器在我的用户模型中使名称和电子邮件唯一。当我尝试在数据库中保存一个重复的用户时,它给了我错误,这是好的,但即使在返回响应后,返回语句下面的代码正在执行,我收到一个错误,说 "错误:发送后无法设置标头。" 这是我的代码。

user.js的:

.codeElement.ace_editor

router.js

var mongoose = require("mongoose")
var uniqueValidator = require("mongoose-unique-validator");
var crypto = require("crypto");
var userSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: [true, 'cant be blank'],
            unique: true,
            match: [/^[a-zA-Z0-9]+$/, "is invalid"],
            index: true
        },
        email: {
            type: String,
            unique: true,
            required: [true, 'cant be blank'],
            index: true
        },
        salt: String,
        password_hash: String
    }, { timestamps: true });

userSchema.plugin(uniqueValidator, { message: "already taken" });

userSchema.methods.setPassword = function (password) {
    this.salt = crypto.randomBytes(15).toString('hex');
    //console.log(this.salt);
    this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');

    //console.log(this.hash);
}
userSchema.methods.checkPassword = function (password) {
    var hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
    return this.hash == hash;
}

var User = module.exports = mongoose.model("User", userSchema);

注意:我还没有添加router.js文件的完整代码。 我知道这个问题的解决方法是在else语句中添加剩余的代码。但我不知道为什么这个错误最初会出现。

我在控制台中遇到的错误是:

//route for Signup


router.get("/signup", function (req, res) {
    res.render('signup.html');
});
router.post('/signup', function (req, res) {
    var name = req.body.name;
    var email = req.body.email;
    var password = req.body.password;
    var verify = req.body.verify;
    if (!name || !email || !password || !verify || password != verify) {
        var passwordError;
        if (password != verify)
            passwordError = 'Password are not matching';
        res.render('signup.html', { 'Error': 'Invalid Details', 'name': name, 'email': email, 'passwordError': passwordError });
        return;
    }

    var newUser = User(
        {
            name: name,
            email: email

        });
    newUser.setPassword(password);
    newUser.save(function (err) {
        if (err) {
            //console.log("Database Error:%s" , err);
            console.log(err);
            // Even after using return statement the code below this 
            // statement is being executed . I dont know why?
            return res.status(500).send({ success: false, message: 'User already exists' });
        }

    });
    console.log("here");

    req.session.user = newUser;
    console.log(newUser);
    res.redirect('/newpost');
});

1 个答案:

答案 0 :(得分:0)

只需使用save返回Promise的事实:

  //Make the route async
 router.post('/signup' , async function(req,res){

   //validate user input
   const { name, email, password, verify } = req.body;
   if(!name || !email || !password || !verify) 
      return res.json({ error:"Wrong data"});
   }

   //create a new user
   const user = User({ name, email });

   // asynchronously save it to db, catch all errors
   try {
     await user.save();
     //return valid response
     return res.json({success: true});
   } catch(e){
     return res.json({error:"dupe"});
  }
});

您的代码无效,因为您无法从回调中返回。返回调用回调的内部函数。