0

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)
    }
})
  • Have you try to put some console.log to see where it gets. For example you could put it just after .then(user => { if(!user) { console.log('in then(user=>',user) – Jose Marin Jan 20 '21 at 19:00
  • user.findOne is asynchronous function which means you call `res.json(loggedInUser)` before you assign the value to `loggedInUser` variable. So instead of this `loggedInUser = req.body.username` do this `res.json(req.body.username)` – Molda Jan 20 '21 at 19:00

0 Answers0