gpt4 book ai didi

javascript - 当尝试通过node.js使用方法函数时,未定义不是一个函数

转载 作者:行者123 更新时间:2023-12-03 08:21:07 24 4
gpt4 key购买 nike

我正在使用node.js开发身份验证功能。因此,当我尝试使用我在顶部制作的methods.comparePassword函数来验证用户在表单上输入的密码时,我收到错误,但不明白为什么?

首先我有这样的 UserSchema。

// user schema
var UserSchema = new Schema({
name: String,
username: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
required: true,
select: false
}
});

var User = mongoose.model('User', UserSchema);

然后我创建了这样的comparePassword 方法。

// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function(password) {
var user = this;

return bcrypt.compareSync(password, user.password);
};

然后我创建了这样的路由来对用户进行身份验证并生成 token 。

apiRouter.post('/authenticate',function(req,res){
// find the user
// select the name username and password explicitly
User.findOne({
username: req.body.username
}).select('name username password').exec(function(err, user) {

if(err) throw err;

// no user with that username was found
if(!user){
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if(user){

// check if password matches

//console.log(req.body.password);
var validPassword = user.comparePassword(req.body.password);
//var validPassword = true; If i use this everything works fine.


if (!validPassword) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {

// if user is found and password is right
// create a token
var token = jwt.sign({
name: user.name,
username: user.username
}, superSecret, {
expiresInMinutes: 1440 // expires in 24 hours
});

// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}

});
});

但是当我向服务器发送请求时,我收到了这样的错误。

var validPassword = user.comparePassword(req.body.password);
^
TypeError: undefined is not a function
at Promise.<anonymous>

然后当我更改 var validPassword = true; 时一切正常。

有人知道如何解决这个问题吗?

谢谢!

最佳答案

确保在创建架构之后、创建模型之前定义这些方法。

// user schema
var UserSchema = new Schema({
name: String,
username: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
required: true,
select: false
}
});

// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function(password) {
var user = this;

return bcrypt.compareSync(password, user.password);
};

var User = mongoose.model('User', UserSchema);

关于javascript - 当尝试通过node.js使用方法函数时,未定义不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33743551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com