'Basic login using ExpressJS, MongoDB and AJAX
I'm trying to make a basic Express login when a user enters an existing username from MongoDB into a prompt:
HTML although not really relevant:
<a href="#home" class="login"><span class="fontawesome-circle"></span></a>
Main.js:
$(document).ready(function(){
$('.login').on('click', login);
});
function login(){
var user = prompt('Username?', '');
$.ajax({
type:'GET',
url: '/users/login',
data: user
}).done(function(response){
console.log(response);
window.location.replace('http://localhost:3030/');
}).fail(function(response){
console.log("Oops not working");
});
}
App.js:
app.get('/users/login', function(req, res) {
const data = req.body;
if(db.users.find({username:data}) > 1){
res.send("nice!");
}else{
res.send("not nice!");
}
})
For now I'd just like to get Nice! when I type "admin" in the prompt, as there is a user is the users collection of "username":"admin" in MongoDB. Currently, I'm getting "Not Nice!" Any ideas why?
Thanks!
Solution 1:[1]
hey you need to try something like this: its my code used for my login modal
app.post("/login", async (req, res) => { const { username, pwd } = req.body;
const userModelInstance = UserModel.getInstance();
const users = await userModelInstance.retrieve({ userId: username });
if (users.length === 0) {
return res.status(404).json({ message: "User not found" });
}
const user = users[0];
console.log(users, user);
if (user.hashPassword !== pwd) {
return res.status(400).json({ message: "Invalid password" });
}
return res.status(200).json(user);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | samuel illouz |
