无法读取nodejs中未定义的属性“修剪”

时间:2019-12-27 12:09:56

标签: javascript node.js

我在nodejs中为我的登录表单编写了一个cleanUp函数,但是当我尝试登录时,会显示此错误。我将usename和email的值设置为一个空字符串,但仍然不起作用。

User.prototype.cleanUp = function () {
    if (typeof (this.data.username) != "string") { this.data.username == "" }
    if (typeof (this.data.email) != "string") { this.data.email == "" }
    if (typeof (this.data.password) != "string") { this.data.password == "" }

    this.data = {
        username: this.data.username.trim().toLowerCase(),
        email: this.data.email.trim().toLowerCase(),
        password: this.data.password
    }
}

这是我的登录方法:

User.prototype.login = function () {
    return new Promise((resolve, reject) => {
        this.cleanUp()
        userCollection.findOne({ username: this.data.username }).then((attemptedUser) => {
            if (attemptedUser && attemptedUser.password == bcrypt.compareSync(this.data.password, attemptedUser.password)) {
                resolve("Login Successfully.")
            } else {
                reject("Login Failed.")
            }
        }).catch(function() {
            reject("Please try again later.")
        })
    })
}

2 个答案:

答案 0 :(得分:1)

就像adiga一样在评论中说:将比较运算符==更改为赋值运算符=

User.prototype.cleanUp = function () {
    if (typeof (this.data.username) !== "string")
        this.data.username = "";
    if (typeof (this.data.email) !== "string")
        this.data.email = "";
    if (typeof (this.data.password) !== "string")
        this.data.password = "";

    this.data = {
        username: this.data.username.trim().toLowerCase(),
        email: this.data.email.trim().toLowerCase(),
        password: this.data.password
    };
}

答案 1 :(得分:-3)

尝试添加 if(this.data.username != null && this.data.email != null) {

像这样

User.prototype.cleanUp = function () {
if(this.data.username != null && this.data.email != null) {
    if (typeof (this.data.username) != "string") { this.data.username == "" }
    if (typeof (this.data.email) != "string") { this.data.email == "" }
    if (typeof (this.data.password) != "string") { this.data.password == "" }

    this.data = {
        username: this.data.username.trim().toLowerCase(),
        email: this.data.email.trim().toLowerCase(),
        password: this.data.password
    }
}
}