我有一个这样定义的全局对象:
var userDatabase = {};
在我的应用程序中,我正在尝试注册新用户。这就是我的函数的样子:
function register(req, res){
var username = req.body.username;
var obj= {count: 0,
password:req.body.password};
//if user is already in the database
if(userDatabase.hasOwnProperty(username)){
res.redirect("/?error=User has already registered");
}
//store user, redirect to home page
else{
userDatabase[username] = obj;
console.log("added new user: ", username, "with properties: ", userDatabase[username]);
//redirect to homepage
res.redirect("/");
}
}
我的问题是我不相信这句话:
userDatabase[username] = obj;
实际上是将我新注册的用户添加到我的对象中,因为当我打印到控制台时,它说我的用户名未定义。
如何正确地将我的用户名存储在我的对象中?谢谢!
编辑:我应该补充一点,我只能使用此代码注册一个用户,当我尝试注册第二个用户时,它会显示“用户已经注册”错误......这让我真的相信我的对象没有做什么我想让它做
这是我在 if/else 语句之前和之后打印出 userDatabase[username] 的值时的控制台日志:
Express server listening on port 3000
before if/else: undefined
added new user: undefined with properties: { count: 0, password: 'abc' }
after if/else: { count: 0, password: 'abc' }
POST /register 302 11ms - 58b
GET / 200 226ms - 803b
GET /libs/jquery/jquery.min.js 304 5ms
GET /libs/bootstrap/css/bootstrap.min.css 304 4ms
GET /stylesheets/style.css 200 55ms - 110b
before if/else: { count: 0, password: 'abc' }
after if/else: { count: 0, password: 'abc' }
POST /register 302 2ms - 126b
GET /?error=User%20has%20already%20registered 200 27ms - 861b
GET /libs/jquery/jquery.min.js 304 2ms
GET /libs/bootstrap/css/bootstrap.min.css 304 1ms
GET /stylesheets/style.css 304 2ms
这里有一些非常错误的东西 - 无法识别我尝试添加的新用户
编辑2:
当我尝试在同一个文件的另一个函数中访问 userDatabase[username] 时,它无法验证 userDatabase{} 中是否存储了该用户。这就是我尝试访问它的方式:
function login(req, res) {
var username = req.body.username;
var password = req.body.password;
req.session.username = username;
req.session.password = password;
loggedInUsers[username] = LoggedIn;
//when login button is pressed
if(userDatabase.hasOwnProperty(username) ){
storedPassword = userDatabase[username].password;
if (storedPassword === password){
//check for correct password
userDatabase[username].count++;
console.log("Count: ", userDatabase[username].count);
res.redirect("/users");
}
}
else{
res.redirect("/?error=Invalid username/password");
}
}
以及注册然后尝试登录后的控制台输出:
Express server listening on port 3000
before if/else: undefined
added new user: undefined with properties: { count: 0, password: 'abc' }
after if/else: { count: 0, password: 'abc' }
POST /register 302 11ms - 58b
GET / 200 232ms - 803b
GET /libs/jquery/jquery.min.js 304 6ms
GET /libs/bootstrap/css/bootstrap.min.css 304 6ms
GET /stylesheets/style.css 200 69ms - 110b
POST /login 302 2ms - 122b
GET /?error=Invalid%20username/password 302 1ms - 68b
GET /users 200 22ms - 430b
GET /libs/jquery/jquery.min.js 304 2ms
GET /libs/bootstrap/css/bootstrap.min.css 304 3ms
GET /stylesheets/style.css 304 1ms