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

How to deploy NodeJS app on server with Apache2 and acess it with Server IP addresss - Node JS deploy project Live.

     hello friens , This is Vasu Birla , in previous post we have seen the deployement of NodeJS app on AWS instance server instance but AWS server is expensive than other servers . SO today we will use simple Ubuntu server for making Live out Project using Apache2 . At the end you will be abe to access your NodeJS app using server IP address from anywhere  .. 1.  Login to your server using SSH terminal . (in AWS part i already explained how to do this )     -> Open your putty in hostname put your server IP -      login with ssh username ->root and password     (if you dont have root username and pass ask your      provider or reset it from cpanel or hosting panel ) 2. after login - on terminal you can Put your project anywhere.     There are two ways to put your project folder on server location     (i) - > using Github - (very popular and easy to track your everyday code changes to your project folder)             you can push your entire project folder to git-hub and and

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  Functions of Router

Part 16- HUB (Networking Devices)- Computer Networking- CCNA

hello friends , Today we will discuss about the second Networking Devices Ethernet HUB. HUB Hub is a centralize device via all devices (computers, printers etc.) are connected with the star topology.  Hub connects other multiple devices together and helps to make connectivity mutually so that they can share and transfer data to each and every devices which is connected to that hub.  Hub does work at the first layer means at Physical layer of the OSI Model. Hub has many ports, and each port works like a repeater so Hub is also known as Multiport Repeater. A Hub Types of Hubs. there are three kind of Hubs. Active , passive and Manageable hubs. 1. Active Hubs - These hubs regenerates and amplify the signals to keep them strong. one more thing there is electricity needed in the active Hubs. 2. Passive Hubs- Passive Hubs simply forward the received signals. this type of hub does not make pure signal or regenerate so  these passive hubs doesn't n