Skip to main content

Creating Login and Registration Application Using NodeJS and MySQL!

Creating Login and Registration Application Using NodeJS and MySQL

Creating Login and Registration Application Using NodeJS and MySQL rather than using any Programming Languages to interact with back-end databases, we are going to use ExpressJS which gives us very good flexibility over Node.js. 

To start with this application required following
1. NodeJS
2. ExpressJS
3. MySQL

Install NodeJS

$  npm install node


Install ExpressJS

$ npm install express --save


Install MySQL

$ npm install mysql--save

Create a database by simply typing a command


mysql> create database test;

Check your database exist in your databases list simply type a command

mysql> show databases; 

Choose the database to work around with select database by typing command

mysql> use test;

Create a users table in that database. To create a users table type command

CREATE TABLE `users`(`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1

Run npm install

It will install all the dependencies. Add all these dependencies to your package.json

To Start With Application.

1. app.js Content

const express = require('express');
const path = require('path');
const hbs = require('hbs'); 
//const web2 = require('../ngo-rest-api/app.js'); 
const web= require('./routes/web.js'); 
var session = require('express-session'); 
var fs = require('fs'); 
var url = require('url'); 
var bodyParser = require('body-parser'); 
const app = express(); 
app.use(session({ secret: 'secret', resave: true, saveUninitialized: true })); app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json()); 
hbs.registerPartials("./views/partials"); 
app.set('view engine', 'hbs'); 
app.set('views', path.join(__dirname, 'views'));
app.use(express.static("./public"));
app.use('/', web); app.listen(1337, () => { console.log('Serving on port .... 1337'); });

2. Create web.js under routes directory.

const express = require('express'); var bodyParser = require("body-parser"); //const mysql = require('mysql'); const { check, validationResult } = require('express-validator'); var mysql = require('mysql'); var session = require('express-session'); var path = require('path'); var https = require('https');
const hbs = require('hbs'); var conn = mysql.createConnection({ host : 'localhost', user : 'root', password : 'tes12', database : 'test' }); conn.connect(function(err){ if(!err) { console.log("Database is connected"); } else { console.log("Error while connecting with database"+err); } });


router.get('/', (req, res) => { res.render('index.hbs', { morris: true }); console.log('Request Url:' + req.url); });

router.post('/users', [ // username must be an email check('username').isLength({ min: 5 }), check('password').isLength({ min: 5 }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { // return res.status(422).json({ errors: errors.array() }); var message="Invalid Login and Password"; res.render('index.hbs', {message: message }); } else { const username = req.body.username; const password = req.body.password; var sess = req.session; sess.username = req.body.username; console.log(sess.username); conn.query("SELECT * FROM users where username =? and password=? ",
[username,password], function (err, result, fields) { if (err) throw err; res.render('dashboard.hbs', { morris: true }); console.log('Request Url:' + req.url); }); } });


3. Required HTML FILE as this file as .hbs not html.


<!DOCTYPE html>
<html lang="en">

{{> head}}

<body>

    <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="login-panel panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Please Sign In</h3>
                    </div>
                    <div class="panel-body">
               <form role="form" method="POST" action="/users">
             <fieldset>
            <h3 >{{message}}</h3>
                    <div class="form-group">
                 <input class="form-control" placeholder="username" name="username" type="username" autofocus>
                                </div>
                                <div class="form-group">
                                    <input class="form-control" placeholder="Password" name="password" type="password" value="">
                                </div>
                                <div class="checkbox">
                                    <label>
                                        <input name="remember" type="checkbox" value="Remember Me">Remember Me
                                    </label>
                                </div>
                                <!-- Change this to a button or input when using this as a form -->
                              
<input class="btn btn-lg btn-success btn-block" type="submit">
                            </fieldset>
                        </form>
I want to <a href="/reg">register</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{> scripts}}

</body>

</html>


Save this file under /view folder.

Let’s run the whole application by simply typing the command
node app.js
ouput will be




Comments

Popular posts from this blog

How to make money on amazon without selling

 While selling products on Amazon is one of the most popular ways to make money on the platform, there are several other ways you can earn money without actually selling products. Here are some ideas: Amazon Affiliate Program: You can earn a commission by promoting other people's products on Amazon through the Amazon Associates program. You can create content on your blog, website or social media channels, and include links to products on Amazon. If someone clicks on the link and makes a purchase, you earn a commission. Amazon Mechanical Turk: Mechanical Turk is a platform that connects businesses and individuals who need tasks done with people who are willing to do them. The tasks can be simple like data entry, image recognition, or tagging, and you can get paid for completing them. Amazon Kindle Direct Publishing: If you enjoy writing, you can self-publish your books on Amazon through the Kindle Direct Publishing program. You can earn up to 70% royalty on your book sales. Amazo...

How to make money from instagram

 How to make money from Instagram  As one of the most popular social media platforms, Instagram has become a hub for influencers and businesses to make money. With over 1 billion active monthly users, there’s no doubt that Instagram is a powerful tool for those looking to monetize their social media presence. If you’re wondering how to make money from Instagram, here’s a step-by-step guide on how to get started. Choose your niche: Before you start to monetize your Instagram account, you need to choose a niche that you’re passionate about. This could be anything from fashion, beauty, food, or travel. Choose a niche that you’re knowledgeable and passionate about, as it will make it easier for you to create engaging content. Create a compelling Instagram profile: Your Instagram profile should showcase who you are and what you’re all about. It’s important to have a clear and concise bio, along with high-quality profile and cover photos. Your profile should reflect your niche and ...

How to Facebook Account Open 2023

   To open a Facebook account, follow these steps: Visit the Facebook website: Open your preferred web browser and go to www.facebook.com. Sign up for an account: On the Facebook homepage, you'll find a sign-up form on the right side. Fill in the required information: Enter your first name and last name in the respective fields. Provide your email address or phone number in the next field. Create a strong and unique password. Select your date of birth using the drop-down menus. Choose your gender by clicking on the appropriate option. Review the terms and policies: Click on the "Sign Up" button. Facebook will present its terms and data policy. It's important to read and understand these terms before proceeding. If you agree to them, click "Accept" or "Agree" to continue.   Verify your account: Facebook will send a confirmation code to the email address or phone number you provided during the sign-up process. Retrieve the code from your email inbox ...