I am trying to write the backend for a simple Login registration application using NodeJS, Express and MongoDB. The registration process works fine but the login process returns an empty response after I send a POST request to the route. Here is the code for the login route:
// login router!
router.route('/login').post((req,res) => {
const { username, password } = req.body
let errors = []
loggedInUser = ""
// match user
user.findOne({ username: username })
.then(user => {
if(!user) {
errors.push({ msg: 'Username is not registered' })
}
// match password
bcrypt.genSalt(10, (err,salt) =>
bcrypt.hash(req.body.password,salt,(err,hash) => {
if(err) throw err
// set password to hash
req.body.password = hash
}))
if(password !== req.body.password) {
errors.push({ msg: 'Password is incorrect!' })
} else {
loggedInUser = req.body.username
}
})
.catch(err => res.status(400).json('Error: ' + err))
if(errors.length > 0) {
res.json(errors)
} else {
res.json(loggedInUser)
}
})