Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

INTRO JavaScript Framework

INTRO JavaScript framework

Uploaded by

swaralasl101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

INTRO JavaScript Framework

INTRO JavaScript framework

Uploaded by

swaralasl101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Introduction to JavaScript Frameworks

Angular, Node.js, React


Overview of JavaScript Frameworks
• Definition: JavaScript frameworks are libraries or collections of pre-
written code that provide developers with tools and utilities to build
web applications more efficiently.
• Importance: JavaScript frameworks simplify development tasks,
enhance code organization, and improve maintainability and
scalability of web applications.
Angular

• Overview: Angular is a front-end JavaScript framework developed and


maintained by Google.
• Features:
• Two-way data binding: Automatically synchronizes data between the model
and view.
• Dependency injection: Allows for modular and reusable code.
• Component-based architecture: Encourages building applications as a
collection of components.
• Use Cases: Ideal for building large-scale, single-page applications
(SPAs) with complex user interfaces.
React
• Overview: React is a front-end JavaScript library developed by
Facebook.
• Features:
• Virtual DOM: Renders user interfaces efficiently by minimizing DOM
manipulation.
• Component-based architecture: Promotes reusability and modular
development.
• JSX (JavaScript XML): Allows developers to write HTML-like syntax within
JavaScript code.
• Use Cases: Ideal for building interactive user interfaces, single-page
applications (SPAs), and mobile apps using React Native.
Node.js
• What is Node.js?
• Node.js is an open source server environment
• Node.js is free
• Node.js runs on various platforms (Windows, Linux,
Unix, Mac OS X, etc.)
• Node.js uses JavaScript on the server
• What Can Node.js Do?
• Node.js can generate dynamic page content
• Node.js can create, open, read, write, delete, and close
files on the server
• Node.js can collect form data
• Node.js can add, delete, modify data in your database
Install Node js (Web Server)
Communication examples

Back End
Front End Node js Server

request(registration)

Server.js

Response(“registration.html”)
Creating New Project

using Visual Studio Code


New project

New project json setup


file
Creating New Project
create new js file

Make Sure To always


save the File

New js file

app.js file

var http = require('http'); is used to include the HTTP module


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World! me now '); Response res
}).listen(8080);

Port Number
To run the app.js

Type the server address


and the port number

To stop the server run hit ctrl+c


Example:
When http://localhost:8080 is requested, the demofile_1.html will be send back to the browser

demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

Create a Node.js file


var http = require('http');
var fs = require('fs'); is used to read files on your computer.
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end(); response
});
}).listen(8080);
Adding Node server to html Based project

Note:
you can at any time convert the html
based project to a node.js based
project by simply
• adding a node server to the project
folder (-npm init)
• and by creating the server.js code
at the root directory to handle all
pages calls and processes
Express Framework
• Express is a minimal and flexible Node.js web application framework that
provides a set of features to develop web and mobile applications.
• It facilitates the rapid development of Node based Web applications.
Following are some of the core features of Express framework −
• Allows to set up middlewares to respond to HTTP Requests.
• Defines a routing table which is used to perform different actions based on HTTP
Method and URL.
• Allows to dynamically render HTML Pages based on passing arguments to
templates.

Installing Express

npm install express --save


Example:
When http://localhost:5000 is requested

const port = 5000


var express = require('express');
var app = express();

app.get('/', function (req, res) {


res.send('Hello World');
response
})

app.listen(port)
Example:
When http://localhost:5000/home.html is requested

var express = require('express');


var app = express();

app.get('/home.html', function (req, res) {


res.send('Home Page');
})

app.listen(5000);
Example GET Method (Login form)
Here is a simple example which passes two values using HTML FORM GET
method. We are going to use process_login router inside server.js to
handle this input login.html
<html>
<body> login.html

<form action = "process_login" method = "GET">


First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln">
<input type = "submit" value = "Submit">
</form>

</body>
</html>
const port = 5000
var express = require('express');
call var app = express();
app.get('/login', function (req, res) {
res.sendFile( __dirname + "/" + "login.html" );

Response })
app.get('/process_login', function (req, res) {
first_name= req.query.fn;
last_name = req.query.ln;
call
res.end("my name is" + first_name + last_name);})
app.listen(port)

Response
<html>
<body>

POST Method <form action = "process_login" method = "POST">


First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln">
<input type = "submit" value = "Submit">
</form>

</body>
</html>

var express = require('express');


var app = express();
app.get('/home', function (req, res) {
res.sendFile( __dirname + "/" + "login.html" );
})
app.use(express.urlencoded({ extended: true }));

app.post('/process_login', function (req, res) {


first_name= req.body.fn;
last_name = req.body.ln;
res.end("my name is " + first_name + " " + last_name);})
app.listen(5000)
})
Debugging in Node.js
Using console.log to print out the variable values during the
run at the terminal line

Example:
console.log (first_name + last_name);
Database Connection
Installing WampSrever (Apache webserver and Mysql database server)
https://sourceforge.net/projects/wampserver/
 ‫ﻓﯾدﯾو ﺗﻧﺻﯾب‬wamp
 https://youtu.be/nckzZSxiS_I

If you cannot install the latest version of wamp due to msvcr120.dll msvcr110.dll missing
error follow this link: https://www.youtube.com/watch?v=j4NNram24GM
Or install XAMPP https://www.apachefriends.org/index.html
Or use a remote MySQL Database Server mywindowshosting.com (free)

start the server by clicking


phpMyAdmin
A popular web-based front-end (written in PHP) called
phpMyAdmin allows developers to access management
tools through a web portal.

Default login:
Username: root
Password: null
API Fetching/Node server API

Front End Back End


Browser
Create, Read, EDIT, DELETE
Fetch
MySql
Html Node
JavaScript Database
API Server
Response
API Fetching/Node server API methods

Sending data

http://localhost

1-Body – JSON object

Client Node
HTML Page API
2-Query string - ?id

3-Parameter - /id
API Fetching/Node server API methods
REST API Fetching Methods (POST, GET, PUT, DELETE)

http://localhos
GET (getting Single Record) Id t

GET (getting LIST of Records)

Client POST (Creating New Record) json


HTML Page Node
API
PUT (updating Record) json +Id

DELETE (Deleting Record) Id


http://localhost

API Fetching/Node server API methods Examples


Server.js

app.get('/process_detail',
GET Single Record
fetch('http:// localhost:5000/process_detail?title=‘ + tt)
query string req. query.title;

GET LIST of Records fetch("http://localhost:5000/process_index ") app.get('/process_index'

app.post('/process_buy
POST json fetch("http:// localhost:5000/process_buy", options); …….
req.body.title,

app.put('/process_update’,
PUT json fetch("http://localhost:5000/process_update",option) …….
req.body.title,

app.delete('/process_delete’,
DELETE fetch("http:// localhost :5000/process_delete?title=" +tt,options query.title;
JavaScript API Fetching

Options Example fetch("http://localhost:5092/......",options)

options = {
method: ‘xx', Post/Put/Delete

headers: {
'Content-Type': 'application/json'
},
(JSON Object)
body: JSON.stringify(xx) Post,Put
}
Rest API Receiving data
http://localhost
Server.js

await response.json(); JSON Array res.end(JSON.stringify(rows)) GET LIST of Records

Client
HTML Page
JSON res.end(JSON.stringify(rows[0])) GET Single Record

await response.text();
text
res.end(" sucessful"); POST DELETE PUT
Insert.html
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" id="ti" class="form-control" required />
</div>
<div class="form-group">
<label for="description">Description:</label>
Note: if you <input type="text" class="form-control" name="description" id="de" required />
</div>
used fetch don’t <div class="form-group">
<label for="price">Price:</label>
use form or <input type="number" name="price" id="pr" class="form-control" required />
</div>
form submission <div class="form-group">
method <label class="control-label">Catagory</label>
<select class="form-control" name="cata" id="ca" >
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option>
</select>
</div>
<button onclick="insert()">Insert</button>
<div id="res"></div>
<script>
async function insert() {
var ti = document.getElementById('ti').value;
var de = document.getElementById("de").value;
var pr = document.getElementById("pr").value;
var ca = document.getElementById("ca").value;
book = { title: ti, price: pr, description: de, cata: ca }
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(book) Local host IP address
}
let response = await fetch("http://127.0.0.1:5000/process_insert", options);
let message = await response.text();
document.getElementById("res").innerHTML = message;
}
</script>
</body>
</html>
Server.js var express = require('express');
1- npm install express
var app = express();
var mysql = require('mysql'); 2- npm install mysql
var cors = require('cors'); 3- npm install cors
app.use(cors({ origin: '*'})); CORS (Cross Origin Resource Sharing)
var con = mysql.createConnection({ To allow remote communication
host: "localhost",
user: "root",
password: "",
database: "test" });
app.use(express.json()); To listen to insert call
app.get('/insert', function (req, res) { To display the insert form
res.sendFile( __dirname + "/" + "insert.html" );
})
app.post('/process_insert',function (req, res) {
var ti=req.body.title;
var pr=req.body.price;
var ca=req.body.cata; To listen to process_ insert method call
var de=req.body.description;

var sql = "INSERT INTO book( title, description, price, cata) VALUES
('"+ti+"','"+de +"','"+pr+"' ,'"+ca+"')";
con.query(sql); To insert book into DB
res.end( "sucessfully added" );
})
app.listen(5000);
index.html
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />

<div id="tb"></div>
</head>
<body>
<button class="btn btn-primary" onclick="getText('http://127.0.0.1:5000/process_index')">Show All Books <span
class="badge badge-light" id="nn"></span>
</button> Local host IP address
<script>
getnumber('http://127.0.0.1:5000/process_index')
async function getnumber(url) {
var response = await fetch(url);
var x = await response.json();
let num = x.length + 1;
document.getElementById("nn").innerHTML = num;
}
async function getText(url) {
var response = await fetch(url);
var x = await response.json();
ta = "<table border='1' class = 'animate__animated animate__fadeInDownBig table'>";
ta += "<tr><th>Id</th><th>Name</th><th>price</th> <th>cata</th> </tr>";
for (i = 0; i < x.length; i++) {
ta += "<tr> <td>" + x[i].Id + "</td><td>" + x[i].title + "</td><td>" +
x[i].price + "</td>" +
"<td>" + x[i].cata + "</td></tr>";
}
ta += "</table>";
document.getElementById("tb").innerHTML = ta;
}
Server.js

app.get('/index', function (req, res) {


res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/process_index', function (req, res) {
// Prepare output in JSON format
var sql = "select * from book";
con.query(sql,function (err, rows, fields) {
res.end(JSON.stringify(rows))
});
})

To send back all books as JSON object


Delete.html

<html lang="en">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<body>
Book title: <input type="text" id="title" > <br>
<div id="res"></div>
<button type="button" onclick="deletetbook()">Delete</button>
<script>
async function deletetbook() {
var tt = document.getElementById('title').value;
let options = {
method: 'DELETE', To call process_delete method using API DELETE
headers: {
'Content-Type': 'application/json;charset=utf-8' },
}
let response = await fetch("http://127.0.0.1:5000/process_delete?title=" +tt,options);
let message = await response.text();
Swal.fire({ To print the success message
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500
}) }
</script></body></html>
Server.js

app.get('/delete', function (req, res) {


res.sendFile(__dirname + "/" + "delete.html");
})
app.delete('/process_delete', function (req, res) {
var tt = req.query.title; To delete book record based on its title
let message = "";
var sql = "delete from book where title= '" + tt + "' ";
con.query(sql, function (err, result) {
if (result.affectedRows > 0) res.send(" sucessfully deleted ");
else res.end(" book not deleted ");
});
})
To send back the successful deleted message as text
<html> <body>
Detail.html
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" id="ti" />
<button onclick="getbook()">search</button>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" name="description" id="de" />
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" name="price" class="form-control" id="pr" />
</div>
<div class="form-group">
<label class="control-label">Catagory</label>
<select class="form-control" name="cata" id="ca">
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option>
</select>
</div>

<script>
async function getbook() {
var dd = document.getElementById('ti').value;
var response = await fetch('http://127.0.0.1:5000/process_detail?title=' + dd);
var x = await response.json();
document.getElementById("de").value = x.description;
document.getElementById("pr").value = x.price;
document.getElementById("ca").value = x.cata
}
</script>
</body> </html>
Server.js

app.get('/detail', function (req, res) {


res.sendFile(__dirname + "/" + "detail.html");
})

app.get('/process_detail', function (req, res) {

var tt = req.query.title;
var sql = "Select * from book where title= '" + tt + "' ";
con.query(sql, function (err, rows, fields) {
res.end(JSON.stringify(rows[0]))
}); To get book record based on its title
})

To send back the first found book as a json object

Security Note:
To prevent this SQL injection, you need to either use the escape() method as follows:
let sql = `SELECT * FROM todos WHERE title = ` + mysql.escape(tt);
change the ……………..
Detail.html code to <div class="form-group">
<label class="control-label">Catagory</label>
allow the update <select class="form-control" name="cata" id="ca">
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option>
</select>
</div>
<button onclick="update()">Update</button>
<div id="res"></div>
<script> Add these codes
………………………………………….
async function update() {
var ti = document.getElementById('ti').value;
var de = document.getElementById("de").value;
var pr = document.getElementById("pr").value;
var ca = document.getElementById("ca").value;
book = { title: ti, price: pr, description: de, cata: ca }
let options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(book)
}
let response = await fetch("http://127.0.0.1:5000/process_update", options);
let message = await response.text();
document.getElementById("res").innerHTML = message;
}
</script>
</body>
</html>
Server.js

app.put('/process_update', function (req, res) {


var ti = req.body.title;
var pr = req.body.price;
var ca = req.body.cata;
var de = req.body.description;

var sql = "update book set description = '" + de + "', price =


'" + pr + "' , cata = '" + ca + "' where title ='" + ti + "'";
con.query(sql, function (err, result) {
if (result.affectedRows > 0) res.send(" sucessfully updated ");
else res.end(" book not updated ");
});
})

YouTube Recording
https://youtu.be/6FxeaPnKV8o
<!DOCTYPE html> buy.html
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
</head>
<body>
<div class="row" id="demo"></div>
<div id="res"></div>
<script>
getText("http://127.0.0.1:5000/process_index");
async function getText(url) {
let response = await fetch(url);
let x = await response.json();
var ta = "";
for (i = 0; i < x.length; i++) {
ta += "<div class='col-md-3 animate__animated animate__fadeInUpBig '>" ;
ta += "<div class='card'>";
ta += "<div class='card-header bg-warning text-center'>" + x[i].Id + "</div>";
ta += "<div class='card-body'>" + x[i].title +"<br>Price: "+ x[i].price +"</div>";
ta += "<div class='card-footer'> <button class='btn btn-info' onclick=buy('" + x[i].price + "') >buy</button> </div>";
ta += "</div> </div>";
}
document.getElementById("demo").innerHTML = ta;
}
buy.html

async function buy(bprice) {


var cid = "100"; should come from the session variable

var bprice = bprice;


order = { customerid: cid, bookprice: bprice } To send the order as a json object
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(order)
}
let response = await fetch("http://127.0.0.1:5000/process_buy", options);
let message = await response.text();
document.getElementById("res").innerHTML = message;
}
</script>
</body>
</html>
app.get('/buy', function (req, res) {
Server.js res.sendFile( __dirname + "/" + "buy.html" );
})

app.post('/process_buy',function (req, res) {


var cid=req.body.customerid;
var pr=req.body.bookprice;

var sql = "INSERT INTO orderbook( custid, total) VALUES ('"+cid+"','"+pr +"' )";
con.query(sql);
res.end( "sucessfully bought" );
})
Example:
File Upload When http://localhost:8081/index.html
is requested
npm install express-fileupload

<html>
<head>
<title>File Uploading Form</title>
</head>

<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "process_file" method = "POST"
enctype = "multipart/form-data">
<div class="form-group">
<label>Select picture:</label>
<input type="file" name="file_pic" class="form-control" accept="image/png, image/jpeg">
</div>
<br />
<input type = "submit" value = "Upload File" />
</form>
</body></html>
var express = require('express');
To server static files such as images, CSS
var app = express(); files, and JavaScript files, use the
// express.static
app.use(express.static('img'));
//file uploading
const fileUpload = require('express-fileupload');
app.use(fileUpload());
// Create the img folder
app.get('/index.html', (req, res) => {
res.sendFile( __dirname + "/" + "index.html" );
})
//
app.post('/process_file', function (req, res) {

var sampleFile = req.files.file_pic;


var uploadPath;

if (!req.files || Object.keys(req.files).length === 0) {


return res.status(400).send('No files were uploaded.');
}

uploadPath = process.cwd() + '/img/' + sampleFile.name;


sampleFile.mv(uploadPath, function(err) {
if (err)
return res.status(500).send(err);
}); The process.cwd() method is an inbuilt application
console.log(sampleFile.name); programming interface of the process module which
res.end( "uploaded sucessfully" ); is used to get the current working directory
})
Delete all book records from the table

Add image attribute to the table


Example: insert book with a pic
<html> <body>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" id="ti" />

</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" name="description" id="de" />
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" name="price" class="form-control" id="pr" />
</div>
<div class="form-group">
<label class="control-label">Catagory</label>
<select class="form-control" name="cata" id="ca">
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option>
</select>
</div>

<div class="form-group">
<label>Select picture:</label>
<input type="file" id="ff" class="form-control" accept="image/png, image/jpeg">
</div>
<button onclick="insert()">Insert</button>
<div id="res"></div>
Add this code
<script>

async function insert() {


var ti = document.getElementById('ti').value;
var de = document.getElementById("de").value;
var pr = document.getElementById("pr").value;
var ca = document.getElementById("ca").value;

var input = document.getElementById('ff')


var data = new FormData()
data.append('upfile', input.files[0]);
data.append('title', ti);
Add this code data.append('description', de);
data.append('price', pr);
data.append('cata', ca);
1-Use FormData not JSON because of sending image
let options = { 2-Remove header content type
method: 'POST',
body: data
}
let response = await fetch("http://127.0.0.1:5000/process_insert", options);
let message = await response.text();
document.getElementById("res").innerHTML = message;
}
</script>
</body> </html>
var express = require('express');
var app = express();
var mysql = require('mysql');
 npm install express
var cors = require('cors');  npm install mysql
app.use(cors({ origin: '*'}));
var con = mysql.createConnection({  npm install cors
host: "localhost", user: "root", password: "", database: "test" });  npm install express-fileupload
//
app.use(express.static('img'));
//file uploading
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.get('/insert', function (req, res) {
res.sendFile( __dirname + "/" + "insert.html" );
})
app.post('/process_insert',function (req, res) { Add this code
var title=req.body.title;
var price=req.body.price;
var cata=req.body.cata;
var description=req.body.description;

if (!req.files || Object.keys(req.files).length === 0) {


return res.status(400).send('No files were uploaded.');
} Check if file is uploaded
var sampleFile = req.files.upfile;
var uploadPath;
uploadPath = process.cwd() + '/img/' + sampleFile.name;
sampleFile.mv(uploadPath, function(err) {
if (err) Uploaded file with under same file name
return res.status(500).send(err);
});
var sql = "INSERT INTO book( title, description, price, cata,image) VALUES ('"+title+"','"+description +"','"+price+"'
,'"+cata+"','"+sampleFile.name+"')";
con.query(sql, function (err, result) {
if (result.affectedRows > 0) res.send(" successfully inserted ");
else res.send(" book not insert ");})
})
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="row" id="catl"></div>
Update the <script>
index.html to getText("http://127.0.0.1:5000/process_index");
Get All JSON async function getText(url) {
let response = await fetch(url);
books at a let x = await response.json();
catalog var ta ="";
for (i = 0; i < x.length; i++) {
ta += "<div class='col-md-3'>" ;
ta += "<div class='card'>";
ta += "<div class='card-header bg-warning text-center'>"+ x[i].title + "</div>";
ta += "<div class='card-body'><img src=http://127.0.0.1:5000/" + x[i].image + " ; width ='50px'>"+ x[i].description
+ "</div>";
ta += "<div class='card-footer'>Price: "+x[i].price +"</div>";
ta += "</div> </div>";
}

document.getElementById("catl").innerHTML = ta;
}
</script>
</body></html>

49
Example: edit and search book with a pic
<html> <body>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" id="ti" onchange="getbook()" /> </div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" name="description" id="de" />
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" name="price" class="form-control" id="pr" />
</div>
<div class="form-group">
<label class="control-label">Catagory</label>
<select class="form-control" name="cata" id="ca">
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option> Add this code
</select>
</div>
<br><img src="" alt="" id="mm" width="150px"><br>
<div class="form-group">
<label>Select picture:</label>
<input type="file" id="ff" class="form-control" accept="image/png, image/jpeg">
</div>
<button onclick="update()">Update</button>
<div id="res"></div>
<script>
async function getbook() {
var dd = document.getElementById('ti').value;
var response = await fetch('http://127.0.0.1:5000/process_detail?title=' + dd);
var x = await response.json();
document.getElementById("de").value = x.description;
document.getElementById("pr").value = x.price;
document.getElementById("ca").value = x.cata;
document.getElementById("mm").src = 'http://127.0.0.1:5000/' + x.image;
}

async function update() {


var ti = document.getElementById('ti').value;
var de = document.getElementById("de").value;
var pr = document.getElementById("pr").value;
var ca = document.getElementById("ca").value;

var input = document.getElementById('ff')


var data = new FormData()
data.append('upfile', input.files[0]); Add this code
data.append('title', ti);
data.append('description', de);
data.append('price', pr);
data.append('cata', ca);

let options = {
method: 'PUT',
body: data
}
let response = await fetch("http://127.0.0.1:5000/process_update", options);
let message = await response.text();
document.getElementById("res").innerHTML = message;
}
app.put('/process_update', function (req, res) {
var ti = req.body.title;
var pr = req.body.price;
var ca = req.body.cata;
var de = req.body.description; Add this code
var sql = "";
var uploadPath;

if (req.files && Object.keys(req.files).length > 0) {


var sampleFile = req.files.upfile;
uploadPath = process.cwd() + '/img/' + sampleFile.name;
sampleFile.mv(uploadPath, function (err) {
if (err)
console.log(err);
});
sql = "update book set description = '" + de + "' , price = '" + pr + "', cata = '" + ca + "',
image = '" + sampleFile.name + "' where title = '" + ti + "' ";
}
else {
sql = "update book set description = '" + de + "' , price = '" + pr + "', cata = '" + ca + "'
where title = '" + ti + "' ";
}

con.query(sql, function (err, result) {


if (result.affectedRows > 0) res.send(" sucessfully updated ");
else res.send(" book not updated ");
});
})
Sessions
• session is associated with a particular user’s visit to your site.
• However, unlike application variables, session variables disappear
after a certain period of user inactivity.

Sharing Data between html Sharing Data between server’ process

• html • process

• html • process
LocalStorage Session
• process
• html
• process
• html
Registration
<html>
<body background="light pink">
<form id="RegForm" action="process_registration" method="post">
<fieldset>
<legend>Registration</legend>
<p>
<label>Username </label><br><br>
<input type="text" name="na" required placeholder="Enter your username"/>
</p>
<p>
<label>Password </label><br><br>
<input type="password" name="pa" id="password1" required placeholder="Enter password"/>
</p>
<p>
<label>Confirm Password </label><br><br>
<input type="password" id="password2" required placeholder="Re-ente password"/>
</p><br>
<p>
<label>email </label><br><br>
<input type="email" name="em" required placeholder="enter email"/>
</p><br>
<input type="submit" value="Submit"/>

</fieldset>
</form>

</body>
</html>
app.get('/registration', function (req, res) {

res.sendFile( __dirname + "/" + "registration.html" );

})
app.post('/process_registration',function (req, res) {
var nn=req.body.na;
var pp=req.body.pa;
var ee=req.body.em;

var sql = "INSERT INTO users( username, password, role, email) VALUES ('"+nn+"','"+pp +"','customer'
,'"+ee+"')";
con.query(sql);
res. redirect ('login');
})
For using Sessions
npm install express-session

<body>
<div class="mx-auto mt-5 bg-light p-5" style="width: 30%;">
<form action = "loginprocess" method = "POST" >

<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" placeholder="Your Name" required />
</div>
<div class="form-group">
<label for="email">Password:</label>
<input type="password" class="form-control" name="pass" placeholder="Your password" required />
</div>
<button type="submit" class="btn btn-info">Log in</button>
</div>

</form>

</body>
var express = require('express');  npm install express
var app = express();
var mysql = require('mysql');  npm install mysql
var cors = require('cors');  npm install cors
app.use(cors({ origin: '*'}));
var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "test" });
 npm install express-fileupload
app.use(express.json());  npm install express-session
app.use(express.static('img'));
const fileUpload = require('express-fileupload');
app.use(fileUpload());
To generate a unique 64 random
var sessions = require('express-session');
app.use(sessions({ secret: "thisismysecrctekeyfhrgfgrfrty84fwir767", saveUninitialized:true, resave: false })); hexadecimal secret key use this web site
https://www.grc.com/passwords.htm,
app.use(express.urlencoded({ extended: true })); Using secret key you could change it
app.post('/loginprocess',function (req, res) {
var nn = req.body.name;
var pp = req.body.pass;
var sql = "select * from users where username = '"+ nn+"' and password = '"+pp+"' " ;
con.query(sql,function (err, rows) {
if (rows.length > 0) { Saving data in sessions in case a valid user
session=req.session;
session.userId=rows[0].Id;
session.username=rows[0].username;
session.userrole= rows[0].role;
res. redirect ('home');
}
else
res.end( "wrong username or password" ); });
})
app.get('/login',function (req, res) {
res.sendFile( __dirname + "/" + "login.html" );
})
To make buy a secure page for customers only

app.get('/buy',function (req, res) {


session=req.session;
Only if the user is verified as a customer then display the buy page
var rol= session.userrole;
if (rol == 'customer')
res.sendFile( __dirname + "/" + "buy.html" );
else
res. redirect ('login');
}) To make insert a secure page for admin only

app.get('/insert',function (req, res) {


session=req.session;
var rol= session.userrole;
if (rol == 'admin')
res.sendFile( __dirname + "/" + "insert.html" );
else
res. redirect ('login');
})
Emails
Your Application might need to send an email notification to users if needed

npm install nodemailer

You need to change your email account security setting to allow sending emails by
an application
e.g. For gemail
https://youtu.be/mg6fxvgEuec
app.post('/process_registration',function (req, res) {
var nn=req.body.na;
var pp=req.body.pa;
var ee=req.body.em;
var sql = "INSERT INTO users( username, password, role, email) VALUES ('"+nn+"','"+pp +"','customer' ,'"+ee+
con.query(sql);

emto= "user@hotmail.com";
title= "successful Registration";;
message="Thank you for your registration";
var nodemailer = require('nodemailer'); To send welcome email after registration
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'aimanturani@gmail.com',
pass: 'xxxxx'
},
tls: {rejectUnauthorized: false }
});
var mailOptions = {
from: 'aimanturani@gmail.com',
to: emto,
subject: title,
text: message
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res. redirect ('login');
All CRUD operation in a single page using modal effects
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body><br>
<button type="button" onclick="insertbook()" class="btn btn-success" data-toggle="modal"
data-target="#myModal">Insert new Book</button> <br>

<div class="modal fade" id="myModal" role="dialog"> To show the myModal when clicked
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Manage Book</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" id="ti" />
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="de" />
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" class="form-control" id="pr" />
</div>
<div class="form-group">
<label class="control-label">Catagory</label>
<select class="form-control" id="ca">
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option>
</select>
</div>
<br><img src="" alt="" id="mm" width="150px"><br>
<div id="picd" class="form-group">
<label>Select picture:</label>
<input type="file" id="ff" class="form-control" accept="image/png, image/jpeg">
</div>
</div>
<div class="modal-footer">
<button id="insert" class="btn btn-info" data-dismiss="modal" onclick="insert()">Insert</button>
<button id="edit" class="btn btn-info" data-dismiss="modal" onclick="update()">Update</button>
<button id="del" class="btn btn-info" data-dismiss="modal" onclick="delet()">Delete</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div> </div> </div></div><br>
<table class="table table-striped" id="demo"></table>
<script>
document.getElementById("edit").style.display = "none"; To control the visibility of modal buttons and the file uploader
document.getElementById("picd").style.display = "none";
document.getElementById("insert").style.display = "none";
document.getElementById("del").style.display = "none";
getList("http://127.0.0.1:5000/process_index");

async function getList(url) {


var response = await fetch(url);
var x = await response.json();
var ta = "<tr><th>Id</th><th>Name</th><th>price</th> <th> </th> </tr>";
for (i = 0; i < x.length; i++) {
ta += "<tr> <td>" + x[i].Id + "</td><td>" + x[i].title + "</td><td>" +
x[i].price + "</td>" +
"<td> <button type='button' onclick=getbook('" + x[i].title + "') class='btn btn-info' data-toggle='modal'
data-target='#myModal'>Detail</button>" +
"<button type='button' onclick=editbook('" + x[i].title + "') class='btn btn-warning' data-toggle='modal' data-
target='#myModal' >edit</button>" +
"<button type='button' onclick=deletebook('" + x[i].title + "') class='btn btn-danger' data-toggle='modal' data-
target='#myModal'>Delete</button>" +
"</td></tr>";
}
document.getElementById("demo").innerHTML = ta;
}
async function getbook(dd) {
var response = await fetch('http://127.0.0.1:5000/process_detail?title=' + dd);
var x = await response.json();
document.getElementById("ti").value = x.title;
document.getElementById("de").value = x.description;
document.getElementById("pr").value = x.price;
document.getElementById("ca").value = x.cata;
document.getElementById("mm").src = 'http://127.0.0.1:5000/' + x.image;
}
function editbook(dd) { To display the modal edit button and
document.getElementById("edit").style.display = "block"; file uploader
document.getElementById("picd").style.display = "block";
getbook(dd);
} to get the book information
function deletebook(dd) {
document.getElementById("del").style.display = "block";
getbook(dd);
}
function insertbook() {
document.getElementById("insert").style.display = "block";
document.getElementById("picd").style.display = "block";
insert();
}
async function insert() {
document.getElementById("insert").style.display = "none"; To the hide the modal insert button and file
document.getElementById("picd").style.display = "none";
var ti = document.getElementById('ti').value; uploader after finish inserting
var de = document.getElementById("de").value;
var pr = document.getElementById("pr").value;
var ca = document.getElementById("ca").value;
var input = document.getElementById('ff')
var data = new FormData()
data.append('upfile', input.files[0]);
data.append('title', ti);
data.append('description', de);
data.append('price', pr);
data.append('cata', ca);
let options = {method: 'POST',body: data }
let response = await fetch("http://127.0.0.1:5000/process_insert", options);
getList("http://127.0.0.1:5000/process_index"); }
To refresh table after insertion
async function update() {
document.getElementById("edit").style.display = "none";
document.getElementById("picd").style.display = "none";
var ti = document.getElementById('ti').value;
var de = document.getElementById("de").value;
var pr = document.getElementById("pr").value;
var ca = document.getElementById("ca").value;

var input = document.getElementById('ff')


var data = new FormData()
data.append('upfile', input.files[0]);
data.append('title', ti);
data.append('description', de);
data.append('price', pr);
data.append('cata', ca);

let options = {
method: 'PUT',
body: data
}
let response = await fetch("http://127.0.0.1:5000/process_update", options);
getList("http://127.0.0.1:5000/process_index");
}
async function delet() {
document.getElementById("del").style.display = "none";
if (confirm("are you sure!") == true) { To confirm the deletion
var tt = document.getElementById('ti').value;
let options = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}
let response = await fetch("http://127.0.0.1:5000/process_delete?title=" + tt, options);
getList("http://127.0.0.1:5000/process_index");
}
}
</script>
</body>
</html>
Multi Line Entry Example
Shopping Cart
Multi Line Entry Example
Shopping Cart

Data JSON object

Item JSON object


Item JSON object
Multi Line Entry Example
Shopping Cart

var data = {
“customer”:”Aiman”,
“item” : [
{“name":“book1",”price”:100,“quant":2},
{“name":“book2",” price”:100,““quant":1},
],
}
cart.html
<html>
<body>
Customer Number: <input type='text' id='cnm'> <br> <br>
Enter Book Name <input type="text" id="tt" onchange="getprice()">
Price <label id="lbl1"></label>
enter quantity <input type="number" id="num" size="5">
<button onclick="add()">Buy</button>

<div id="res"></div>
<br>
<table border="1" id="tbl"></table>
<button onclick="checkout()">Check out</button>

<script>
pp = "";
cartItems = [];

function add() {
item = { name: tt.value, price: lbl1.innerHTML, quant: num.value, };
cartItems.push(item);
display();
lbl1.innerHTML = ""; tt.value = ""; num.value = "";
}
async function getprice() {
var dd = document.getElementById('tt').value;
var response = await fetch('http://127.0.0.1:5000/process_detail?title=' + dd);
var x = await response.json();
document.getElementById("lbl1").innerHTML = x.price;
}
function display() {
var ta = "My Shopping Cart<tr><th>Name</th><th>Price</th> <th>quantity</th><th></th> </tr>";
for (var i = 0; i < cartItems.length; i++) {
ta += "<tr><td>" + cartItems[i].name + "</td><td>" + cartItems[i].price + "</td> <td>" +
cartItems[i].quant + " </td> <td><button class='btn btn-info' onclick=del('" + cartItems[i].name + "')
>Delete</button> </td></tr>";
}
document.getElementById("tbl").innerHTML = ta;
}

function del(nn) {
for (var i = 0; i < cartItems.length; i++) {
if (cartItems[i].name == nn) {
cartItems.splice(i, 1);
}
}
display();
}
async function checkout() {

cn = document.getElementById("cnm").value;
order = { customer: cn, itemlines: cartItems }
let options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(order)
}
let response = await fetch("http://127.0.0.1:5000/process_cart", options);
let myText = await response.text();
document.getElementById("res").innerHTML = myText;
document.getElementById("cnm").value = "";
document.getElementById("tbl").innerHTML = "";
}
</script></body></html>
app.get('/cart.html', function (req, res) {
res.sendFile(__dirname + "/" + "cart.html");
})
app.post('/process_cart', function (req, res) {
var cn = req.body.customer;
var orline = req.body.itemlines;

var sql = "INSERT INTO orderbook( custid, total) VALUES ('" + cn + "','0' )";
con.query(sql);

var sql = "Select * from orderbook where custid= '" + cn + "' order by id desc ";
con.query(sql, function (err, rows, fields) {
var ordid = rows[0].id; Getting the created order Id
tot = 0;
orline.forEach(myFunction);

function myFunction(bk) {

var bkn = bk.name;


var bkp = bk.price;
var bkq = bk.quant;

sql = "insert into orderline (orderid,itemname,itemquant,itemprice) values ( '" +


ordid + "' ,'" + bkn + "' ,'" + bkq + "','" + bkp + "') ";
con.query(sql);
tot += bkp * bkq; For each book in the cart save it into order line table
}

sql = "UPDATE orderbook SET total = '" + tot + "' where Id ='" + ordid + "' ";
con.query(sql);
res.end("sucessfully bought"); To update the order total value
});
Using EJS Template
Sending Data From Server to html file (without using fetch)
Detail.html

x
Server Data
Cannot send data to html pages
(without fetch)

Detail.ejs

Server Data
id Can send data to ejs pages
Using EJS Template

ejs page
Convert
ejs page
to html

calling
page
Using EJS Template Engine in Nodejs Project
var express = require('express');
var app = express();
var mysql = require('mysql');
1- npm install express
var cors = require('cors');
app.use(cors({ origin: '*'})); 2- npm install mysql
var con = mysql.createConnection({
host: "localhost", 3- npm install cors
user: "root", 4- npm install express-fileupload
password: "",
database: "test" });
app.use(express.json());
5- npm install ejs
app.use(express.static('img'));
//file uploading
const fileUpload = require('express-fileupload');
app.use(fileUpload());

app.use(express.urlencoded({ extended: true }));

app.set('views', './views');
app.set('view engine', 'ejs');
To set up this middleware:
views is the folder where our all pages (ejs files) will be kept.
to setup the view engine to use ejs template
<html>
<%- include('head')-%>
<body>
<div class="form-group">
Title:<%= ti %>
</div>
<div class="form-group">
Description: <%= de %>
</div>
<div class="form-group">
Price:<%= pr %>
</div>
<div class="form-group">
<img src=<%= im %> height="150px">
</div>
<a class='btn btn-info' href='manage' >Go Back to Book List</a>
</body>
</html>

app.get('/search_book',function (req, res) {


Id = req.query.id;
var sql = "select * from book where Id = '"+Id+"' ";
con.query(sql,function (err, rows) {
res.render('search', {ti:rows[0].title,pr:rows[0].price,de:rows[0].description,im:rows[0].image});
});
}) ejs file Data
Used to show ejs files
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style>
.s-panel{
margin-bottom:10%;
height: 210px;
background-color:aliceblue
}
</style>

app.get('/dashboard', function (req, res) {


let d1 = 0;
let d2 = 0;
var sql = "select count(Id) as cc from book where cata = '1' ";
con.query(sql, function (err, rows) {
d1 = rows[0].cc ;
});
var sql = "select count(Id) as cc from book where cata = '2' ";
con.query(sql, function (err, rows) {
d2 = rows[0].cc ;
d3 = d1 +d2;
console.log (d1,d2,d3)
res.render('dash', { cata1: d1 , cata2: d2, total: d3});
});
});
<h1>DashBoard</h1>
<html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Books');
data.addRows([
['CS', <%= cata1 %>],
['IT', <%= cata2 %>]
]);
var options = {
'title': 'Number of Books',
'width': 400,
'height': 300
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<%- include('head')-%>
</head>
<body>
<div id="chart_div"></div>
<div class="row">
<div class="col-md-2">
<div class='card'>
<div class='card-header bg-warning text-center'>Computer Science</div>
<div class='card-body'><img src='cata1.png' ; height='50px'></div>
<div class='card-footer'>Number of Books <div>
<%= cata1 %>
</div>
</div>;
</div>
</div>
<div class="col-md-2">
<div class='card'>
<div class='card-header bg-warning text-center'>Information Technology</div>
<div class='card-body'><img src='cata2.jpg' ; height='50px'></div>
<div class='card-footer'>Number of Books <div>
<%= cata1 %>
</div>
</div>;
</div>
</div>
<div class="col-md-2">
<div class='card'>
<div class='card-header bg-warning text-center'>Total Books</div>
<div class='card-body'><img src='total.jpg' ; height='50px'></div>
<div class='card-footer'>Number of Books <div>
<%= total %>
</div>
</div>;
</div>
</div> </div> </body></html>
How to Deploy Your Node.js website (on Heroku)
https://www.youtube.com/watch?v=r2S89Hm1Uq0
1- change your database to remote connection (mywindowshosting)
2- Create Account at: https://www.heroku.com/
3- download cli version for windows
4- also download Git https://git-scm.com/download/win
5- npm install -g heroku
6- from power shell window cmd
heroku login
7- go to your project Folder
$ cd my-project/
$ git init
$ heroku git:remote -a jsnode-test-aiman
$ git add .
8- Add your name and email
Git config --global user.email "aimann…"
Git config --global user.name "aiman"
9- // after any change
$ git commit -am "make it better"
$ git push heroku master

You might also like