0

I am new to js/node/express, and I have been working on this application where I have the following code to handle user registration:

const Account = require('../models/Account.js')

module.exports = {
  // TODO: Check why Postman hangs on POST request for this
  async register (req, res, next) {
    if (req.body.email && req.body.password) {
      var newAccount = new Account()
      newAccount.email = req.body.email
      newAccount.password = newAccount.generateHash(req.body.password)

      const account = Account.create({email: newAccount.email, password: newAccount.password}, function (err, res) {
        if (err) {
          console.log('could not insert. Check error.')
          // CANT CALL res.status(400).send({ error: 'email already exists'})
          res.status(500)
          return next(err)
        }
        res.status(400).send({
          error: 'exists'
        })
      })
      console.log(`inserted account ${newAccount.email}`)
      res.send(account.toJSON())
    }
  }
}

I read this post about how to properly send JSON data back in order to build a proper REST API but ran into some issues.

When I do the call to res.status(400) I get an error that res.status is not a function. Is that because res is not available in that if statement? If it isn't how then, do I properly send a 400 (or any error status) in a case like this?

I want to be able to send an error message if the saving into my mongo db fails, or send back the created user if the insertion was successful.

If there is anything out there that I can read Id love to read some of that as well.

mufc
  • 695
  • 3
  • 16
  • 31

1 Answers1

2

When I do the call to res.status(400) I get an error that res.status is not a function.

That's because you are defining res as an argument to the callback in this line:

const account = Account.create({email: newAccount.email, password: newAccount.password}, 
    function (err, res) {

And that res hides the higher scoped res. The solution is to not have a name conflict. Change the name of this res to be accountRes or something like that. You have to be aware of name conflicts in declared argument names when nesting inline functions.


It also looks like:

res.send(account.toJSON())

is in the wrong place. You will send that BEFORE Account.create() finishes its asynchronous work. That probably needs to be inside the callback.


Speaking of proper error handling, if this if (req.body.email && req.body.password) test fails, then you don't send any response at all. You need to always send some sort of response to an http request. I'd suggest adding an else to that if and send an appropriate response.

jfriend00
  • 683,504
  • 96
  • 985
  • 979