I’m new to node.js, im trying to make a simple login form, i have a database with the users and passwords, this is the action asigned to the form:
app.post('/auth',async(req, res) => { const user = req.body.user; const pass = req.body.pass; if(user && pass){ connection.query('SELECT user, pass FROM users WHERE user = ? AND pass = ?', [user, pass], async(error, results) =>{ if(results.length == 0 || pass != results[1]){ res.send('INCORRECT USER OR PASSWORD '); }else{ res.send('LOGGED IN'); } }) } })
but when i press the submit button in the browser window it stays loading forever
Advertisement
Answer
You want to always return something to the client. In the case where the username or password is missing, you are not sending anything.
app.post('/auth',async(req, res) => { const user = req.body.user; const pass = req.body.pass; if(user && pass){ connection.query('SELECT user, pass FROM users WHERE user = ? AND pass = ?', [user, pass], async(error, results) =>{ if(results.length == 0 || pass != results[1]){ res.send('INCORRECT USER OR PASSWORD '); }else{ res.send('LOGGED IN'); } }) }else{ res.send('MISSING USER OR PASSWORD '); } })
Also, it could happen that the database query never executes the callback because the connection was not made before the query. So check your connection and make sure it’s established before this query is made.