属性(读取'"/>
“错误”:创建用户时“无法读取未定义的属性(读取'
我正在尝试向 Web 应用程序添加一些身份验证,并且我正在使用一个用于注册 mongoose 的功能,注册功能在这里:
userSchema.statics.signup = async function(username, email, password){
//validation
if(!email || !password || !username){
throw Error('All fields required');
}
if(!validator.isEmail(email)){
throw Error('Email is Not Valid');
}
if(!validator.isStrongPassword(password)){
throw Error('Password not strong enough');
}
const userExists = await this.findOne({username});
const emailExists = await this.findOne({email});
if(userExists){
throw Error('Username in use')
}
if(emailExists){
throw Error('Email in use')
}
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(password, salt);
const user = await this.create({username, email, password: hash})
}
然后在发送到这里的post请求的函数中调用这个函数:
const signupUser = async (req, res) => {
const {username, email, password} = req.body;
try{
const user = await User.signup(username, email, password);
//create token
const token = createToken(user._id);
res.status(200).json({username,email,token})
}catch(error){
res.status(400).json({error: error.message})
}
}
用户创建得很好,但问题出在响应对象上,当我在邮递员中发送请求时,我得到的响应是:
{
"error": "Cannot read properties of undefined (reading '_id')"
}
我读过其他类似的 stackoverflow 问题,收到此错误并尝试了这些解决方案,但没有一个有效。我还在 signupUser 函数中将用户记录到控制台,它返回未定义,但在注册函数中,我还记录了用户的值,它返回一个对象,其中包含我希望用户在 signupUser 函数中返回的所有数据
回答如下:问题是
signup
函数不返回任何内容(或 undefined)。这一行就是问题所在: const user = await User.signup(username, email, password);
您正在调用 signup
函数,并将其返回值——记住,nothing!——分配给一个变量。然后,当您尝试访问所述变量的属性时,您会收到错误,因为您正在读取任何内容的属性。通过使用您在函数中声明的用户变量向 signup
添加 return 语句,您应该能够解决问题。
更多推荐
“错误”:创建用户时“无法读取未定义的属性(读取'
发布评论