error in authentication

Asked

Viewed 23 times

-1

Cannot read property 'username' of null

Keeps giving this error I don’t know why, he can create a new user but can’t login, someone knows what is happening?

 app.post('/users', async (req, res) => {
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)
    const user = { username: req.body.username, password: hashedPassword }
    await userModel.create(user)
    res.status(201).send()
  } catch {
    res.status(500).send()
  }
})

app.post('/users/login', async (req, res) => {
  const user = await userModel.find(user => user.username === req.body.username)
  if (user == null) {
    return res.status(400).send('Cannot find user')
  }
  try {
    if (await bcrypt.compare(req.body.password, user.password)) {
      res.send('Success')
    } else {
      res.send('Not Allowed')
    }
  } catch {
    res.status(500).send()
  }
})

1 answer

0

had not called me, but instead of using the userModel.find(user => user.username === req.body.username) should use the userModel.findOne({username: req.body.username})

is that I was using a fake database with arrey format and forgot to change

Browser other questions tagged

You are not signed in. Login or sign up in order to post.