![](/img/trans.png)
[英]TypeError: Cannot read property 'trim' of undefined Node Js firebase functions
[英]TypeError: Cannot read property 'trim' of undefined in Node application
我正在開發 javascript 應用程序,並在控制器中有 MVC model 有一個 userController.js 文件,在模型中,清理 ZC1C425268E68385D1AB5074C17A94F14 文件夾中有一個 user.js。 為什么我收到 TypeError: Cannot read property 'trim' of undefined this error
//User.js files code goes here
let User = function (dataUser) {
this.dataUser = dataUser
this.errors = []
}
// 在清理 function 中,我檢查了輸入類型字符串,然后通過使用修剪和小寫屬性避免任何虛假條目,但我收到一個錯誤,即無法讀取未定義的屬性“修剪”這個錯誤
User.prototype.cleanUp = function () {
if (typeof this.dataUser.username != "string") {
this.dataUser.username = ""
}
if (typeof this.dataUser.email != "string") {
this.dataUser.username = ""
}
if (typeof this.dataUser.password != "string") {
this.dataUser.username = ""
}
this.dataUser = {
username: this.dataUser.username.trim().toLowerCase(),
email: this.dataUser.email.trim().toLowerCase(),
password: this.dataUser.password
}
}
User.prototype.login = function (callback) {
this.cleanUp()
usersCollection.findOne({ username: this.dataUser.username }, (err, attemptedUser) => {
if (attemptedUser && attemptedUser.password == this.dataUser.password) {
callback("Success")
} else {
callback("Invalid username / password")
}
})
}
// userController.js code
exports.login = function (req, res) {
let user = new User(req.body)
user.login(function (result) {
res.send(result)
})
}
這意味着您要在dataUser
中修剪的鍵不存在。 因此,要修復它,您必須在執行trim()
操作之前進行 if 檢查。 你可以這樣寫:
this.dataUser = {
username: this?.dataUser?.username?.trim().toLowerCase(),
email: this?.dataUser?.email?.trim().toLowerCase(),
password: this?.dataUser?.password
}
這是解決此問題的最短方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.