Skip to main content

SignUP & Login API using MYSQL Database - NodeJS, Express Js, MYsql

//  create a new folder and setup Node JS in it using command npm init   
// install required node dependencies (express, bcyrptjs, body-parser, nodemon) using command 'npm install express' & same for other modules 

Project Architecture - refer Image - and create your Dirs & files inside 


// edit package.json files -

put your server file name (here app.js) in the main section - (refer above picture) 
as well in scripts  put "start":"nodemon" inplace of dev - so that you will have to run command once npm start -  each time you will edit app.js file it will be auto refreshed  on cmd or terminal - 

open your folder in cmd and use npm start after making app.js - 


//app.js file - 

================== app.js Start ======================================= 
const express = require('express');
const connection = require('./connection.js');
const bodyParser = require('body-parser');
const { signupValidation } = require('./validation');
const { validationResult } = require('express-validator');
const {hashPassword, comparePassword} = require('./helper.js');

const app = express(); 
app.use(bodyParser());


app.post("/register",(req,res)=>{

  var userDetails = req.body;

   userDetails.password = hashPassword(userDetails.password);

  connection.query('INSERT INTO register(_id,username,name,email,password,mobile)VALUES(?,?,?,?,?,?)',

     [
          userDetails._id,
          userDetails.username,
          userDetails.name,
          userDetails.email,
          userDetails.password,
          userDetails.mobile 
        ]

  )

     res.status(200).json({success: true,userDetails: { _id: userDetails._id, email: userDetails.email, }});      
 });

app.post("/login",(req,res)=>{

     var userDetails = req.body;

     const {email} = userDetails;

 
      let checkUser =  connection.query('SELECT * FROM register WHERE email = ?', [email], (err, rows) => {
    if (err) {  
        return console.error('Error executing query', err.stack);
    }
 
    //console.log(rows[0].password);
    //console.log(userDetails.password)

    let isValid = comparePassword(userDetails.password, rows[0].password);
    if(isValid)
      res.send("Login successfull !")
      else 
      res.send("Wrong Password")
});     

})

app.listen(3000); 
console.log("express Server Started");

=================== app.js End ====================================== 


Now for connectivity with MySql database create connection.js file 

=======================connection.js Start ================================ 
var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'root',      // Replace with your database username
  password: '',      // Replace with your database password
  database: 'userapi' // // Replace with your database Name
}); 
 
conn.connect(function(err) {
  if (err) throw err;
  console.log('mysqlDB is connected successfully !');
});
module.exports = conn;

===================connection.js End====================================

Saving Plain password in database is like sin for developers, so we are going to save password in the hashed form -  and after that at the time of login  compare plain Password to hashed form password-  

===================== helper.js=======================================

const bcrypt = require('bcryptjs');

 module.exports.hashPassword = function (password){

const salt = bcrypt.genSaltSync(); 
return bcrypt.hashSync(password, salt); 

}

module.exports.comparePassword = function (raw, hash){

return bcrypt.compareSync(raw, hash)
}

//module.exports {hashPassword, comparePassword }  //=> for ES6 Node js  Dont use here 

=================== helper.js end ==================================== 

now what you want to get saved by user whether it is name or email or password - we should use validator in which we can specify the requirement for perticular field for example there must be unique email or  password length must be 6 minimum  

=============== validation.js  Start ====================================

const { check } = require('express-validator');
 
exports.signupValidation = [
    check('username', 'Name is requied').not().isEmpty(),
    check('name', 'Name is requied').not().isEmpty(),
    check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
    check('password', 'Password must be 6 or more characters').isLength({ min: 5 }),
    check('mobile', 'Mobile is requied').isLength({ min: 10 })

]

==================== validation end =============================== 

Now Test These APIs  on Postman app 

// Testing of  register or SignUp API 


//  Login API Testing 




====================== Thank You ==========================================


#nodejs #expressJs #coder , #Programming
Location Detected  
Sanawad Coordinates
22.1800° N, 76.0700° E

Comments

Popular posts from this blog

Part 15- What is Repeater (Networking Devices)- Computer Networking- CCNA

Repeater  hello friends i am Vasu Birla and today i am starting new segment of CCNA computer networking  its a Networking Devices. we will discuss every important Devices used in networks. Repeater is a first networking devices. What is Repeater  Repeater is a device that receives signals and re-transmits by amplifying or regenerating signals. Repeater has two port one is for receive signals from previous network and second port is for retransmit signals to the next extended network. Two Port Repeater Repeater is a device which is used to Regenerate or replicate signal (Pichhe se aa rahe signal ko regenerate karke ya amplify karke aage strong signals bhej sakte he) Analog and digital both type of signals can be retransmitted by repeater. Here there is difference between regeneration and amplifying.  Amplification means , received signals will be amplified as it is , whether there are impurities in signals  and Regeneration means repeate...

GitHub Repo Collaboration Work on single project

 =============================================== To collaborate effectively with your friend on the same project, you should use Git branches to manage different lines of development. Here's a step-by-step procedure you can follow to streamline collaboration: 1. Create Separate Branches for Each Developer Create a New Branch for Your Friend: On your local repository, create a new branch for your friend. For example if your friend name is kilvish , if you want to create a branch named kilvish , you would run: make sure you would be on main branch already   command->  git checkout -b kilvish git push origin kilvish 2. Set Up Your Friend’s Environment( On your Friend's System )  at kilvish side  run ->  Clone the Repository (if not already done): If your friend hasn’t cloned the repository yet, they should do so: command ->  git clone https://github.com/Vasu-Birla/your-repo.git   // your your main clone line  Fetch All Bran...

Part 19- Router (Networking Devices)- Computer Networking- CCNA

Hello friends...i am Vasu Birla and today will discuss about the most important Networking Device ..Router.  so let's start... ROUTER Router is a device which connect two or more networks together, which is why router is also known is Inter-networking device also. Inter-networking means two or more networks are connected together with the help of router. one more thing router is just like a computer  but it is designed for routing only, our computer can be router also but that are software router while hardware router which are specialize for routing is more efficient and fast than software router.  There is a Operating System installed on router which get moves data from one network to another network with the help of routing table.  Router does work on Network layer or Layer 3 of the OSI model.  Cisco Router There many companies which manufacture Router but main companies are - Cisco , Juniper , HP, 3com and Nortel  ...