0

I'm trying to implement a basic user registration flow using Express.js and mySQL. This is the code I have at the moment (stripped for brevity):

register(app, db) {
        app.post('/register', (req, res) => {
            let email = req.body.email
            let password = req.body.password
            
            try {
                // add the user to the database
                var q_params = [email, bcrypt.hashSync(password, 9)]
                db.query("INSERT INTO users VALUES (?, ?)", q_params, (err) => {
                    if (err) {
                        throw err
                    }
                })
            } catch (err) {
                // respond with an error if one is encountered
                res.json({
                    success: false,
                    msg: err
                })
                return
            }

            // respond with success if everything else goes ok
            res.json({
                success: true,
                email: email
            })
        });
    }

The problem is that no matter the outcome of the code in the try block, I am always getting success: true. How come the error response is never triggered? Is there a better way to be handling this scenario?

1 Answers1

0

I'm assuming the issue is that the nothing is waiting for the db.query() function to finish executing. It's not async and not awaiting that function to resolve. So the last res.json({}) gets hit right away.

I would try to rewrite the code to either use promises or to use that callback function passed to .query(), maybe something like this:

app.post('/register', (req, res) => {
   let email = req.body.email
   let password = req.body.password      
     
   // add the user to the database
   var q_params = [email, bcrypt.hashSync(password, 9)]
   db.query("INSERT INTO users VALUES (?, ?)", q_params, (err) => {
       if (err) {
           return res.json({
              success: false,
              msg: err
           });
        }

        res.json({
           success: true,
           email: email
        });
   });

});

GabrielMC
  • 288
  • 2
  • 7
  • You could also try to use promises to make this async/await. See this https://stackoverflow.com/questions/36547292/use-promise-to-process-mysql-return-value-in-node-js – GabrielMC Sep 03 '21 at 13:53