Javascript Bcrypt比较问题节点

Javascript Bcrypt比较问题节点,javascript,node.js,Javascript,Node.js,我有两个功能,第一个负责向数据库添加用户模型,第二个负责比较密码。但是比较是行不通的 module.exports.signup = function (req, res) { if (req.body == null) { res.status(400); return res.end('Bad juju'); } else { let exists; User.findOne({ username: req.body.username }),

我有两个功能,第一个负责向数据库添加用户模型,第二个负责比较密码。但是比较是行不通的

module.exports.signup = function (req, res) {
if (req.body == null) {
    res.status(400);
    return res.end('Bad juju');
} else {
    let exists;
    User.findOne({ username: req.body.username }),
        (err, doc) => {
            if (doc) {
                exists = true;
                return;
            }
        };
    if (exists) {
        res.setHeader('user-exists', true);
        res.redirect('/signup');
    } else {
        bcrypt.hash(req.body.password, 10, function (hashE, hash) {
            if (hashE) {
                throw hashE;
            }
            new User({
                username: req.body.username,
                email: req.body.email,
                password: hash,
            }).save();
        });
        return res.redirect('/login');
    }
}
};

module.exports.login = function (req, res) {
if (req.body.tosignup) {
    return res.redirect('/signup');
}
if (req.body == null) {
    res.status(400);
    return res.end('Bad request');
} else {
    User.findOne({ username: req.body.username }, (err, doc) => {
        if (err) throw console.log(err);
        console.log(doc.password);
        console.log(req.body.password);
        bcrypt.hash(req.body.password, 10, (err, s) => {
            console.log(s);
        });
        bcrypt.compare(req.body.password, doc.password, (err, succ) => {
            if (err) {
                throw err;
            }
            console.log(err);
            console.log(succ);
            if (succ) {
                res.setHeader('username', doc.username);
                return res.redirect('/welcome');
            } else {
                res.setHeader('password-wrong', true);
                return res.redirect('/login');
            }
        });
    });
}
};

我寻找了不同的来源,他们都说这一种方法是正确的,但每次我尝试使用它时,它都不起作用

我在nodejs中使用bcrypt时遇到了类似的问题。为了解决这个问题,我从npm bcrypt切换到npm bcryptjs(),并使用了以下方法:

NPM要求:

const bcrypt = require('bcryptjs');
要比较密码,可以使用以下代码:

async function compareIt(password, hashedPassword) {
  const validPassword = await bcrypt.compare(password, hashedPassword);
  return validPassword;
}

compareIt(password, passwordBD).then(v => {
    if (v == true) {
        console.log("Equal");
    } else {
        console.log("Not equal");
    }
});
要散列密码,可以使用此函数:

async function hashIt(password) {
  const salt = await bcrypt.genSalt(6);
  const hashed = await bcrypt.hash(password, salt);
  return hashed;
}

没用。。同样的问题,即使密码是一样的,它也不能正确加密。有趣的是,一步一步地写出来效果很好。我想这都是关于异步的。是的,你需要使用异步才能正常工作