Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





How to create Registration & Login form usingn Node.Js with MySql Database?

In this Tutorial we learn how to create registration form and login application in node.Js with MySql Database.

First Install Node.Js in your System.

Install Node Express JS

c:\myproject> express --view=ejs nodeapp
C:\> npx express --view=ejs crud_api
// here crud_api is the project directory.
######################### OR #######################
c:\myproject> npx express --view=ejs nodeapp
here, nodeapp is the project directory of your node application.

install some others required pacakges

express js project structure looks like:

node.Js project structure

after that, you need to required to install some other packages of node.Js.

install some others required pacakges

File Name :

c:\myproject>nodeapp> npm install
c:\myproject>nodeapp> npm install express-flash --save
c:\myproject>nodeapp> npm install express-session --save
c:\myproject>nodeapp> npm install express-validator --save
c:\myproject>nodeapp> npm install method-override --save
c:\myproject>nodeapp> npm install mysql --save

Create Table in your Database.

File Name :

CREATE DATABASE IF NOT EXISTS `node_db` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `node_db`;

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
primary key('id'), `name` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `users` (`id`, `name`, `password`, `email`) VALUES (1, 'sana', 'sana', 'sana@gmail.com');

// ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

Create DB connection

create lib directory in nodeapp and create db_connection.js file in this directory.

File Name : db_connection.js

var mysql=require('mysql');
var conn=mysql.createConnection({
host:'localhost',
user:'root',
password:'password',
database:'node_db'
});
conn.connect(function(error){
if(!!error){
console.log(error);
}else{
console.log('Connected!:)');
}
});
module.exports = conn;

Import Packages and routes in app.js

create app.js file in your root directory(nodeapp) we need to include all packages in app.js file

File Name : app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');


var mysql = require('mysql');
var connection = require('./lib/db');

var authRouter = require('./routes/auth');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
secret: 'mahi*786',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))

app.use(flash());
app.use(expressValidator());

app.use('/auth', authRouter);



// Handling requests that do not match the cases.
/*
app.use((req, res, next) => {
res.status(404).send(
"<h1>Page not found on the server</h1>")
}); */

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});
// port must be set to 3000 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
console.log('Node app is running on port 3000');
});
module.exports = app;

Create Route

route file name auth.js inside the routes folder.

File Name : routes/auth.js

var express = require('express');
var router = express.Router();
var connection = require('../lib/db');
//display login page
router.get('/', function(req, res, next){
res.render('auth/login', {
title: 'Login',
email: '',
password: ''
})
})
//display login page
router.get('/login', function(req, res, next){
res.render('auth/login', {
title: 'Login',
email: '',
password: ''
})
})

//authenticate user
router.post('/login-action', function(req, res, next){
var email = req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM users WHERE email = ? AND password = ?', [email, password], function(err, rows, fields) {
if(err) throw err
// if user not found
if (rows.length <= 0) {
req.flash('error', 'Please correct enter email and Password!')
res.redirect('/auth/login')
}
else { // if user found
// render to views/user/edit.ejs template file
req.session.loggedin = true;
//req.session.name = name;
req.session.name = email;
res.redirect('/auth/home');
}
})
})



//display login page
router.get('/register', function(req, res, next){
res.render('auth/register', {
title: 'Registration Page',
name: '',
email: '',
password: ''
})
})


// user registration
router.post('/post-register', function(req, res, next){
req.assert('name', 'Name is required').notEmpty() //Validate name
req.assert('password', 'Password is required').notEmpty() //Validate password
req.assert('email', 'A valid email is required').isEmail() //Validate email
var errors = req.validationErrors()
if( !errors ) { //No errors were found. Passed Validation!
var user = {
name: req.sanitize('name').escape().trim(),
email: req.sanitize('email').escape().trim(),
password: req.sanitize('password').escape().trim()
}
connection.query('INSERT INTO users SET ?', user, function(err, result) {
//if(err) throw err
if (err) {
req.flash('error', err)
res.render('auth/register', {
title: 'Registration Page',
name: '',
password: '',
email: ''
})
} else {
req.flash('success', 'You have successfully signup!');
res.redirect('/auth/login');
}
})
}
else { //Display errors to user
var error_msg = ''
errors.forEach(function(error) {
error_msg += error.msg + '<br>'
})
req.flash('error', error_msg)
/**
* Using req.body.name
* because req.param('name') is deprecated
*/
res.render('auth/register', {
title: 'Registration Page',
name: req.body.name,
email: req.body.email,
password: ''
})
}
})

//display home page
router.get('/home', function(req, res, next) {
if (req.session.loggedin) {
res.render('auth/home', {
title:"Dashboard",
name: req.session.name,
});
} else {
req.flash('success', 'Please login first!');
res.redirect('/auth/login');
}
});
// Logout user
router.get('/logout', function (req, res) {
req.flash('success', 'Login Again Here');
req.session.destroy();
res.redirect('/auth/login');
});
module.exports = router;

Create Html Views of Login and Registration Page

In this step, you need to create one folder name Auth. So go to the views folder in your app and create the Auth folder.

login.ejs

File Name :

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<% if (messages.error) { %>
<p style="color:red"><%- messages.error %></p>
<% } %>
<% if (messages.success) { %>
<p style="color:green"><%- messages.success %></p>
<% } %>
<form action="/auth/login-action" method="post" name="form1">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">
</div>
<input type="submit" class="btn btn-primary" value="SignIn">
<a href="/auth/register" class="btn btn-success ml-2">Register Here</a>
</form>
</body>
</html>

create registration form register.ejs

File Name : register.ejs

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<% if (messages.error) { %>
<p style="color:red"><%- messages.error %></p>
<% } %>
<% if (messages.success) { %>
<p style="color:green"><%- messages.success %></p>
<% } %>
<form action="/auth/post-register" method="post" name="form1">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="name" name="name" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter name" value="">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">
</div>
<input type="submit" class="btn btn-primary" value="Register">
<a href="/auth/login" class="btn btn-success ml-2">Login</a>
</form>
</body>
</html>

create home page home.ejs

File Name : home.ejs

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<% if (messages.error) { %>
<p style="color:red"><%- messages.error %></p>
<% } %>
<% if (messages.success) { %>
<p style="color:green"><%- messages.success %></p>
<% } %>
<div class="card">
<div class="card-header">
Dashboard <b><%= name %></b>
</div>
<div class="card-body">
<h5 class="card-title">Welcome</h5>
<p class="card-text">You have successfully login</p>
<a href="/auth/logout" class="btn btn-primary">Logout</a>
</div>
</div>
</div>
</body>
</html>

Run Development Server

File Name :

c:myproject\nodeapp> node app.js

http://127.0.0.1:3000/auth/login





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here