gpt4 book ai didi

javascript - MongoDB + Express : How to verify login credentials using db. collection().findOne() 还是 .find()?

转载 作者:IT老高 更新时间:2023-10-28 12:31:26 24 4
gpt4 key购买 nike

我有一个带有用户凭据的 POST 请求作为登录页面的对象,并像这样传递到 API 服务器:

  loginUser(creds) {
//creds is in the form of { username: bob, password: 123 }

var request = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(creds),
}

fetch(`http://localhost:3000/api/login`, request)
.then(res => res.json())
.then(user => {
console.log(user);
console.log('Successful')
})
.catch(err => {
console.log('Error is', err)
})
},

API Server 像这样接收它:

//With .findOne()
app.post('/api/login/', function(req, res) {
console.log('Req body in login ', req.body)
db.collection('users').findOne(req.body, function(err, isMatch) {
console.log('ISMATCH IS: ' + isMatch)
if(err) {
console.log('THIS IS ERROR RESPONSE')
res.json(err)
} else {
console.log('THIS IS ISMATCH RESPONSE')
res.json(isMatch)
}
})
})

//With .find()
app.post('/api/login/', function(req, res) {
console.log('Req body in login ', req.body)
//console logs correctly as { username: bob, password: 123 }
db.collection('users').find(req.body).next(function(err, isMatch) {
console.log('ISMATCH IS: ' + isMatch)
if(err) {
console.log('THIS IS ERROR RESPONSE')
res.json(err)
} else {
console.log('THIS IS ISMATCH RESPONSE')
res.json(isMatch)
}
})
})

因此,使用传入的登录凭据,在 API 服务器中,我想搜索我的 'users' 数据库,看看是否有任何与传入的凭据匹配。但在这两种情况下,isMatch 始终为 null 并始终记录 console.log('THIS IS ISMATCH RESPONSE'),即使用户凭据与数据库中的任何凭据都不匹配.在客户端,我从来没有收到任何错误响应并且总是记录 console.log('Successful')

似乎无法弄清楚我错过了什么。我可能做错了什么?

谢谢

最佳答案

我建议你先找到用户,然后比较密码,比如:

db.collection('users').findOne({ username: req.body.username}, function(err, user) {
console.log('User found ');
// In case the user not found
if(err) {
console.log('THIS IS ERROR RESPONSE')
res.json(err)
}
if (user && user.password === req.body.password){
console.log('User and password is correct')
res.json(user);
} else {
console.log("Credentials wrong");
res.json({data: "Login invalid"});
}
});

关于javascript - MongoDB + Express : How to verify login credentials using db. collection().findOne() 还是 .find()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39759287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com