NodeJS Login and Registration Authentication using mysql
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
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
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... } } });
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.