Skip to content
pakainfo

Pakainfo

Web Development & Good Online education

  • Home
  • Blog
  • Categories
  • Tools
  • Full Form
  • Guest Post
    • Guest Posting Service
  • Advertise
  • About
  • Contact Us

NodeJS Login and Registration Authentication using mysql

June 23, 2018 Pakainfo Technology, Mysql, Mysqli, Node.js, php, Programming Leave a comment

NodeJS Login and Registration Authentication using mysql

Contents

  • NodeJS Login and Registration Authentication using mysql
    • Handling user login and registration using nodejs and mysql
    • Related posts

In this Post We Will Explain About is NodeJS Login and Registration Authentication using mysql With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to How to create a login page in Node.js with MySQL in ExpressExample

In this post we will show you Best way to implement Login and Singup authentication using NodeJS MySQL ExpressJS, hear for Create Form Login And Authentication on MySQL, Node.jswith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Handling user login and registration using nodejs and mysql

First we need to create simple a new table in MYSQL database for simple registering new students.

CREATE TABLE `students` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `student_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `student_father_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Project Structure

β”œβ”€β”€ node_modules
β”œβ”€β”€ package.json
β”œβ”€β”€ routes
β”‚   └── loginroutes.js
└── server.js

Here is simple package.json for more reference and node js npm installing all the more dependencies:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.16.0",
    "express": "^4.14.0",
    "mysql": "^2.13.0"
  }
}

server.js

Now start with create a server.js source code which is as Below:

var express    = require("express");
var login = require('./routes/loginroutes');
var bodypars = require('body-parser');

var liveApp = express();
liveApp.use(bodypars.urlencoded({ extended: true }));
liveApp.use(bodypars.json());

//access control allow origin handles
liveApp.use(function(datarequest, dataresults, next) {
    dataresults.header("Access-Control-Allow-Origin", "*");
    dataresults.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
var router = express.Router();

//simple nodejs test route
router.get('/', function(datarequest, dataresults) {
    dataresults.json({ message: 'welcome to our upload module apis' });
});

//here Nodejs using route to handle simple user registration form
router.post('/register',login.register); //for registration
router.post('/login',login.login) // for login
liveApp.use('/api', router);
liveApp.listen(5000);

loginroutes.js

Also Read This πŸ‘‰   How to Validate Date String in Laravel?

Now lets created with handler some functions in loginroutes.js and
First we need to create mysql Connect databse using specifying the database of select:

var mysql      = require('mysql');
var db_connect = mysql.createConnection({
  host     : 'Pakainfo.com',
  user     : 'root',
  password : '[email protected]#$%^^125',
  database : 'w3free'
});
db_connect.connect(function(err){
if(!err) {
    console.log("Good Luck Your Database is connected ...");
} else {
    console.log("Sorrey Error connecting database.");
}
});

And Then we create new handler for Students registration Form

exports.register = function(datarequest,dataresults){
  var crdate = new Date();
  var students={
    "student_name":datarequest.body.student_name,
    "student_father_name":datarequest.body.student_father_name,
    "email":datarequest.body.email,
    "password":datarequest.body.password,
    "created":crdate,
    "modified":crdate
  }
  db_connect.query('INSERT INTO students SET ?',students, function (error, respnose, fields) {
  if (error) {
    console.log("Sorry error ocurred.!!",error);
    dataresults.send({
      "code":400,
      "failed":"Sorry error ocurred!!"
    })
  }else{
    console.log('The Live solution is: ', respnose);
    dataresults.send({
      "code":200,
      "success":"Good Luck Students registered sucessfully"
        });
  }
  });
}

And then nex steps is handler for Students login and validating Students credentials:

exports.login = function(datarequest,dataresults){
  var email= datarequest.body.email;
  var password = datarequest.body.password;
  db_connect.query('SELECT * FROM students WHERE email = ?',[email], function (error, respnose, fields) {
  if (error) {
    dataresults.send({
      "code":400,
      "failed":"Sorrey error ocurred!!"
    })
  }else{
    if(respnose.length >0){
      if([0].password == password){
        dataresults.send({
          "code":200,
          "success":"Good Luck login sucessfull"
            });
      }
      else{
        dataresults.send({
          "code":204,
          "success":"Sorry Email and password does not match"
            });
      }
    }
    else{
      dataresults.send({
        "code":204,
        "success":"Sorry Email does not exits"
          });
    }
  }
  });
}

First we check if students email exists in database and then check students password for allowing successful login.

we can use tools like Simple postman API tools from chrome apps for sending post some requests to server Side after starting it using the this command

node server.js

Here is simple postman request JSON format for Students registration and login data:

Registration:
url:localhost:5000/api/register
payload:{
"student_name":"DSP Patel",
"student_father_name":"live24u",
"email":"[email protected]",
"password":"[email protected]"
  }
payload type:raw (Application/json)

Login:
url:localhost:5000/api/login
payload:{
	"email":"[email protected]",
	"password":"[email protected]#$458"
}
payload type:raw (Application/json)

and then add simple encryption format layer to store your passwords securely.We are simple going to use methods bcrypt module which simple can be installed by following npm command run

npm install --save bcrypt

loginroutes.js

Update the register handler in loginroutes.js as Below Code:

bcrypt.hash(datarequest.body.password, 5, function( err, bcryptedPassword) {
   
   var students={
     "student_name":datarequest.body.student_name,
     "student_father_name":datarequest.body.student_father_name,
     "email":datarequest.body.email,
     "password":bcryptedPassword,
     "created":crdate,
     "modified":crdate
   }
   ...
  });

loginroutes.js

Also Read This πŸ‘‰   Nodejs Login and Registration with PHP MySQL and SQLite Example

In order to simple format decrypt your the encryption password when user simple tries to login data modify login simple handler in loginroutes.js as simple source code follows:

db_connect.query('SELECT * FROM students WHERE email = ?',[email], function (error, respnose, fields) {
  if (error) {
   //... some code
  }else{
    if(respnose.length >0){
      bcrypt.compare(password, respnose[0].password, function(err, doesMatch){
        if (doesMatch){
     dataresults.send({
       "code":200,
       "success":"Good Luck login sucessfull!!!"
         });
      }else{
     dataresults.send({
       "code":204,
       "success":"Sorrey Email and password does not match!!!"
         });
      }
    });
    }
    else{
      //some source code...
    }
  }
  });

Example

I hope you have Got What is javascript – How to make login form in node.js using mysql database And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

Related posts:

  1. Nodejs Login and Registration with PHP MySQL and SQLite Example
  2. Create a Registration and Login System with PHP and MySQL
  3. jQuery Ajax Secure Login Registration System in PHP and MySQL
  4. CodeIgniter Simple User Registration and Login System
  5. NodeJS RESTful CRUD API and MYSQL – node js Restify Tutorial
  6. registration and signin form in php and mysql with validation
creating registration and login form in node.js and mongodbcreating registration and login form in node.js and mysqlcreating registration and login form in node.js and mysql githublogin form with express js and mysqlnode js login form mysqlnode js login tutorialnode js user authentication using mysql and express jsnode js user registration example

Post navigation

Previous Post:Apache Virtual Host Tutorials – Setup Apache Virtual Hosts with Ubuntu
Next Post:jQuery Slide Effect toggle Direction – slideToggle Animation

Advertise With Us

Increase visibility and sales with advertising. Let us promote you online.
Click Here

Write For Us

We’re accepting well-written informative guest posts and this is a great opportunity to collaborate.
Submit a guest post to [email protected]
Contact Us

Freelance web developer

Do you want to build a modern, lightweight, responsive website quickly?
Need a Website Or Web Application Contact : [email protected]
Note: Paid Service
Contact Me

Categories

3movierulz (64) Ajax (464) AngularJS (377) ASP.NET (61) Bio (109) Bollywood (108) Codeigniter (175) CSS (98) Earn Money (93) Education (63) Entertainment (130) fullform (87) Google Adsense (64) Highcharts (77) History (40) Hollywood (109) JavaScript (1359) Jobs (42) jQuery (1423) Laravel (1088) LifeStyle (53) movierulz4 (63) Mysql (1035) Mysqli (894) php (2133) Programming (2345) Python (99) Software (178) Software (90) Stories (98) tamilrockers (104) Tamilrockers kannada (64) Tamilrockers telugu (61) Tech (147) Technology (2416) Tips and Tricks (130) Tools (214) Top10 (507) Trading (95) Trending (77) VueJs (250) Web Technology (113) webtools (200) wordpress (166) World (343)

A To Z Full Forms

Access a complete full forms list with the meaning, definition, and example of the acronym or abbreviation.
Click Here
  • Home
  • About Us
  • Terms And Conditions
  • Write For Us
  • Advertise
  • Contact Us
  • Youtube Tag Extractor
  • Info Grepper
  • Guest Posting Sites
  • Increase Domain Authority
  • Social Media Marketing
  • Freelance web developer
  • Tools
Pakainfo 9-OLD, Ganesh Sco, Kothariya Ring Road, Chokadi, Rajkot - 360002 India
E-mail : [email protected]
Pakainfo

Β© 2023 Pakainfo. All rights reserved.

Top
Subscribe On YouTube : Download Source Code
We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype Guest Posting Sites