【发布时间】:2021-02-15 20:11:37
【问题描述】:
我正在创建一个 react-native 应用程序。
流程是这样的,客户必须输入电子邮件和密码才能注册,数据将保存在数据库中。在保存数据之前,我使用了 pre-hook beforeValidate 来使用 bcrypt 对密码进行哈希处理。
到这里为止,一切正常,但是当从 instanceMethod comparePassword 做出承诺时,我似乎无法返回 true。
我有一个客户模型 Customer.js 文件,如下所示:
const Sequelize = require('sequelize');
const bcrypt = require('bcrypt');
const db = require('../config/database');
const Customer = db.define('customer', {
id : {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
email : {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password : {
type: Sequelize.STRING,
allowNull: false
},
createdAt : {
type: Sequelize.NOW
},
updatedAt : {
type: Sequelize.NOW
}
}, {
hooks: {
afterValidate: (customer) => {
customer.password = bcrypt.hashSync(customer.password, 10);
}
},
instanceMethods: {
comparePassword: (candidatePassword) => {
return new Promise((resolve, reject) => {
bcrypt.compareSync(candidatePassword, this.password, (err, isMatch) => {
if(err) {
return reject(err);
}
if(!isMatch) {
return reject(false);
}
resolve(true);
});
});
}
}
});
module.exports = Customer;
还有一个 authRoutes.js 文件的 sn-p,如下所示:
router.post('/login', async (req, res) => {
const { email, password } = req.body;
if ( !email || !password ) {
return res.status(422).send({error: 'Must provide email and password!'});
}
const customer = await Customer.findOne({ where: {email} });
if(!customer) {
return res.status(422).send({error: '1. Invalid email or password!'});
}
try {
await customer.comparePassword(password);
const token = jwt.sign({ email }, 'MY_SECRET_KEY');
res.send({ email, token });
} catch(err) {
return res.status(422).send({error: '2. Invalid email or password!'});
}
});
没有错误或任何东西,但即使我输入了正确的凭据,它也总是会捕获“2.无效的电子邮件或密码”错误。任何形式的帮助表示赞赏。谢谢。
【问题讨论】:
-
catch中err的值是多少? -
另外,
bcrypt提供了一个 promise api。您不需要使用Sync函数或创建新的 Promise -
@Matt 它在邮递员上返回“错误”:“2.无效的电子邮件或密码!”`
-
我指的是catch作用域中的
err变量。 -
@Matt 对不起,我也很困惑。从上面的代码中,我无法准确指出错误是什么。是拒绝(错误)还是拒绝(假)?但我在错误上做了一个 console.log,上面写着
TypeError: customer.comparePassword is not a function。
标签: node.js sequelize.js bcrypt