node.js

Create a Login Form With Node.js & MySQL

In our previous example, we saw how we can create a registration form using Node.js and MySQL.

Using that same setup, let us proceed to authenticate the user after he has completed his registration.

First, we create an HTML form for the user to enter his login credentials.

We create a login.html file

<html>  
<body>  
 
<form action="authenticate-controller" method="POST">  
 
Email: <input type="text" name="email">
Password: <input type="password" name="password">
   
<input type="submit" value="Submit">  
</form>
 
   
</body>  
</html> 

Next, we create a script that will authenticate the user. Let us create a file called authenticate-controller.js.

Read Node.js documentation

var Cryptr = require('cryptr');
cryptr = new Cryptr('myTotalySecretKey');
 
var connection = require('./config');
module.exports.authenticate=function(req,res){
    var email=req.body.email;
    var password=req.body.password;
   
   
    connection.query('SELECT * FROM users WHERE email = ?',[email], function (error, results, fields) {
      if (error) {
          res.json({
            status:false,
            message:'there are some error with query'
            })
      }else{
       
        if(results.length >0){
  let decryptedString = cryptr.decrypt(results[0].password);
            if(decryptedString){
                res.json({
                    status:true,
                    message:'successfully authenticated'
                })
            }else{
                res.json({
                  status:false,
                  message:"Email and password does not match"
                 });
            }
          
        }
        else{
          res.json({
              status:false,    
            message:"Email does not exits"
          });
        }
      }
    });
}

Finally we test our authentication script and see the results.

View Comments

Recent Posts

ReferenceError vs. TypeError: What’s the Difference?

When debugging JavaScript, you’ll often encounter ReferenceError and TypeError. While both indicate something went wrong,…

10 hours ago

document.querySelector() vs. getElementById(): Which is Faster?

When selecting DOM elements in JavaScript, two common methods are document.querySelector() and document.getElementById(). But which…

10 hours ago

npm vs. Yarn: Which Package Manager Should You Use in 2025?

When starting a JavaScript project, one of the first decisions you’ll face is: Should I…

3 days ago

Why Learn Software Development? (And Where to Start)

Software development is one of the most valuable skills you can learn. From building websites…

6 days ago

JavaScript Multidimensional Arrays

In JavaScript, arrays are used to store multiple values in a single variable. While JavaScript…

2 weeks ago

What is Containerization

Containerization is a lightweight form of virtualization that packages an application and its dependencies into…

2 weeks ago