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
mysql> show databases;
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1
It will install all the dependencies. Add all these dependencies to your package.json
const express = require('express');
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
Choose the database to work around with select database by typing command
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 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
Comments
Post a Comment