我正在尝试在我的快速API中实现登录功能。以下是我的控制器和与身份验证过程相关的模型功能。
import User from '../models/user.model';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
dotenv.config({path: './src/.env'});
const jwtSecret = process.env.JWT_SECRET;
function login(req, res, next) {
var username = req.body.username;
var password = req.body.password;
User.login(username, password)
.then(user => {
if (user) {
const token = jwt.sign({
userId: user._id
}, jwtSecret);
res.json({
token,
username: user.userName
});
}
res.send('No such user exists!');
})
.catch(e => next(e));
}
export default { login };
userSchema.statics = {
list() {
return this.find().exec();
},
login(username, password) {
var queryPromise = this.findOne({ "userName": username }).exec();
queryPromise.then(function(user) {
bcrypt.compare(password, user.password, function(err, isMatch){
if (err) throw err;
console.log('Is password match :', isMatch);
if (isMatch) {
return;
}
});
});
}
}
这是我遇到的错误
TypeError:无法读取属性'然后'未定义的
有人可以告诉我我在这里做错了吗?
答案 0 :(得分:2)
如果要使用.then
login(username, password) {
return new Promise((resolve, reject) => {
var queryPromise = this.findOne({ "userName": username }).exec();
queryPromise.then(function(user) {
bcrypt.compare(password, user.password, function(err, isMatch) {
if (err) throw err;
console.log('Is password match :', isMatch);
if (isMatch) {
return resolve(user); // pass the user if you want to access it in the .then statement
} else {
return reject(new Error('Invalid Credentials'));
}
});
});
})
}