【问题标题】:Password Validation fails using express使用 express 密码验证失败
【发布时间】:2021-02-28 07:35:46
【问题描述】:

我在尝试注册新用户时收到错误 ValidationError: Path password is required。我是 Node、编程和身份验证的新手。

这是我拥有的用户模型和架构代码,我试图彻底评论它。

用户路由器

router.post("/register", async (req, res) => { 尝试 { 让 {email, password, passwordCheck, displayName} = req.body;

    // validate email, password and passwordCheck
    if (!email || !password || !passwordCheck)
        return res.status(400).json({ msg: "Not all fields have been entered." });
    if (password.length < 5)
        return res.status(400).json({ msg: "The password needs to be at least 5 characters long." });
    if (password !== passwordCheck)
        return res.status(400).json({ msg: "Passwords do not match. Enter the same password twice for verification." });


   //verify if the new user already exists in the MongoDB
    const existingUser = await User.findOne({ email: email });
    if (existingUser)
        return res.status(400).json({ msg: "An account with this email already exists." });

    if (!displayName) displayName = email; //if no display name, email is display name

    const salt = await bcrypt.genSalt(10); //creates random string used for hashing password
    const passwordHash = await bcrypt.hash(password, salt, function (err, hash) {
        if (err) {
            console.log('Issue with hashing bcrypt');
        }// else {console.log('Successful Hash: ' + hash);} add if error checking
    });
    //save new user to DB with hashed password
    const newUser = new User({
        email,
        "password":passwordHash,
        displayName,
    });
    console.log(newUser);
    const savedUser = await newUser.save(); //save the new user to database
    res.json(savedUser); //respond to front end with saved user

} catch (err) {
    console.log('Error registering user');
    res.status(500).json({ err });} });

用户模型

const userSchema = new mongoose.Schema({
email: {type: String, required: true, unique: true},
password: {type: String, required: true, minlength: 5},
displayName: {type: String} });

【问题讨论】:

    标签: javascript node.js express mern insomnia


    【解决方案1】:

    您是否尝试过password: passwordHash 而不是"password": passwordHash。 如果它没有帮助,那么你应该 console.log 你的 passwordHash 以检查它是否有一个值。

    【讨论】:

    • 感谢您的回复。我做了 console.log 我的 passwordHash 并注意到它是未定义的;意识到我不需要回调函数。
    猜你喜欢
    • 1970-01-01
    • 2020-09-21
    • 2015-04-19
    • 2012-09-14
    • 2017-10-17
    • 2017-04-03
    • 2016-05-27
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多