You are on page 1of 74

CE377: Advanced Web Technology 19DCE061

Practical – 1

Aim: Installing and Exploring nodeJS Module System.


1.Download NodeJs:

2. Click the above Run (Run), the following interface:

DEPSTAR(CE) 1
CE377: Advanced Web Technology 19DCE061

3.Select the option to accept the agreement, click next (Next) button:

4.Node.js default installation directory is "C: \ Program Files \ nodejs \", you can modify the
directory, and click next (next):

DEPSTAR(CE) 2
CE377: Advanced Web Technology 19DCE061

5: Click the tree icon to select the mode you need to install, and then click Next next (Next)

DEPSTAR(CE) 3
CE377: Advanced Web Technology 19DCE061

6: Click Install (install) to start the installation Node.js. You can also click Back (Back) to
modify the previous configuration. And then click next (next):

Installation process:

7.Click Finish (complete) button to exit the installation wizard.

DEPSTAR(CE) 4
CE377: Advanced Web Technology 19DCE061

8. View node version:

NPM (Node Package Manager) Installation:


NPM is the default package manager for Node.js that is completely written in Javascript. It helps
in managing the packages and modules required for Node.js functioning and provides a
command line client npm. Packages in Node.js are the entities which bundle up all the necessary
files that are required for a module. Now, by modules, I mean the JavaScript libraries which can
be incorporated in your project. Apart from this, using package.json file, Node.js can easily
install all the required dependencies of the project. Also, you can update or install various
packages using npm.

Practical – 2
Aim: Using Express.js, Create Node.js Web App.

DEPSTAR(CE) 5
CE377: Advanced Web Technology 19DCE061

1.We already installed Node.js, create a directory to hold our application, and make that our
working directory:
$ mkdir MyExpressProject
$ cd MyExpressProject

2. Use the npm init command to create a package.json file for your application. For more
information on how package.json works, see Specifics of npm’s package.json handling.
$ npm init

3. Now install Express in the myapp directory and save it in the dependencies list.
$ npm install express --save

4.Create one folder names public which contains photos , HTML and CSS File of our Website.

5..After that Create app.js file:


const express = require('express')
const app = express()
app.use(express.static(__dirname+"/public"))

app.get("/",(req,res)=>{
    res.sendFile("index.html")
})
app.get("/home",(req,res)=>{
    res.send("HomePage")
})
app.get("/about",(req,res)=>{
    res.send("About Page")
})

app.listen(3001,()=>console.log("Listening the port 3001"))

6.Run Our Code:

DEPSTAR(CE) 6
CE377: Advanced Web Technology 19DCE061

7.Our Website is run completely.

Practical – 3

Aim: Design Dynamic Layout using Template Engines Handlebars.

DEPSTAR(CE) 7
CE377: Advanced Web Technology 19DCE061

Program Code:

//index.js
const express = require("express");
const path = require('path');
const exhb = require('express-handlebars');
const app = express();
app.engine('hbs', exhb({ extname: 'hbs', defaultLayout: "main", }))
app.set('view engine', 'hbs');
app.set("views", path.join(__dirname, "views"));
app.set("layouts", path.join(__dirname, "views", "layout"));
app.use(express.static(__dirname + "/public"));
app.get('/', (req, res) => { res.send("Hello World"); });
app.get("/res", (req, res) => {
res.render("main", { 'layout': 'temp', 'title': 'Dynamic Hanlebars', "content": "Dynamic Content
Using Express Hadlebars", "name": "DEPSTAR" });
});
app.listen(3000, () => { console.log("App is Running on Port 3000") });

//main.hbs View File


<!DOCTYPE html>
<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">
<title>{{title}}</title>
</head>

DEPSTAR(CE) 8
CE377: Advanced Web Technology 19DCE061

<body>
{{content}}
{{{body}}}
</body>
</html>

//temp.hbs Layout File


<h1>HEllo</h1>
<h1>Inside Layout ...</h1>
<h1>{{name}}</h1>

Output:

Practical – 4

Aim: Create Weather App using Asynchronous Node.js.

DEPSTAR(CE) 9
CE377: Advanced Web Technology 19DCE061

Program Code:
//index.js
const express = require('express');
const http = require('https');
const handlebars = require('express-handlebars');
const path = require('path');
const fs = require('fs');
const app = express();
app.use(express.static(__dirname + "/public"));
const arr = [];
app.engine('hbs', handlebars({
extname: 'hbs', defaultLayout: "main", helpers: {
doCelcius: function (a, b) {return (a - b).toFixed(2);}}
}))
app.set("view engine", 'hbs');
app.set("views", path.join(__dirname, "views"));
app.set("layouts", path.join(__dirname, "views", "layout"));
function doReq(params) {
return new Promise(function (resolve, reject) {
// Do async job
let req = http.get('https://api.openweathermap.org/data/2.5/weather?q=' + params +
'&appid=22cad6c160886adcd5ce9f47c4b91a49', function (res) {
res.setEncoding('utf8');
let responseBody = '';
res.on('data', (chunk) => {responseBody += chunk;});
res.on('end', () => {resolve(JSON.parse(responseBody));});
});
req.on('error', (err) => {reject(err);});

DEPSTAR(CE) 10
CE377: Advanced Web Technology 19DCE061

req.end();
});
}
async function getData(params) {return await doReq(params);}
app.get("/", (req, res) => {res.render("sec", { 'layout': "sec" });});
app.get('/api', (req, res) => {
console.log("Nams is " + req.query.name);
getData(req.query.name).then((d) => {
res.render('home', { 'layout': 'sec', 'weather': d['weather'], 'main': d['main'], 'wind': d['wind'],
'icon': "https://openweathermap.org/img/wn/" + d['weather'][0]['icon'] + "@2x.png" })
}).catch(err => { res.statusCode = 402; console.log(err.toString()); if
((err.toString().localeCompare("data is not defined")) == 0) { res.statusMessage = "No City
Found"; } else { res.statusCode = 402; res.statusMessage = "Either You Are Offline or Internal
Server Error" } res.send(); });
});
app.listen(3000, () => {console.log("Running on PORT 3000");})
//sec.hbs Layout File
<!DOCTYPE html>
<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="bootstrap.css">
<title>Document</title>
<style>
.container {
padding: 15px 10px;background: linear-gradient(rgba(0, 0, 0, 0.4),
rgba(0, 0, 0, 0.4)), url("android_weather_app.webp");}
.weather {height: 100%;width: 100%;}

DEPSTAR(CE) 11
CE377: Advanced Web Technology 19DCE061

.icon img {height: auto;width: auto;}


table {font-size: 40px;font-weight: bolder;padding: 10px 10px;}
</style></head>
<body>
<div class="container text-white">
<h1><center>Weather App</center></h1><br><br><br>{{{body}}} <br><br><br>
</div></body></html>

//home.hbs view
<div class="weather"><div class="hide"></div><div class="main">
<div class="icon"><center><img src="{{icon}}" alt="icon"></center></div>
<div class="data">
<center>{{#each weather}}<h1>{{this.main}}</h1><h1>{{this.description}}</h1>{{/each}}
<h1 style="font-size:80px;">{{doCelcius main.temp 273.15}} &#8451</h1></center>
<table class="table text-white table-borderless">
<tbody>
<tr><th scope="row"></th><td>Min/Max</td>
<td>{{doCelcius main.temp_min 273.15}}/{{doCelcius main.temp_max 273.15}}</td>
</tr><tr><th scope="row"></th><td>Pressure</td><td>{{main.pressure}}</td></tr>
<tr><th scope="row"></th><td>Humidity</td><td>{{main.humidity}}</td></tr>
<tr><th scope="row"></th><td>Wind Speed</td><td>{{wind.speed}}</td></tr>
<tr><th scope="row"></th><td>Wind Degree</td><td>{{wind.deg}}</td></tr>
</tbody></table></div></div></div>
//sec.hbs View File
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">City Name:</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter
City Name" required>

DEPSTAR(CE) 12
CE377: Advanced Web Technology 19DCE061

<br><button type="submit" class="btn btn-primary mb-3" id="submit">Submit</button>


<div class="error" id="error"></div></div><script>
let data = document.getElementById('exampleFormControlInput1');
let data1 = document.getElementById('error');
document.getElementById('submit').addEventListener('click', () => {
window.location.href = "/api?name=" + data.value;});
</script>

Output:

Practical – 5
Aim: Data Storage and Retrieval using nodeJS
Program Code:
//index.js
const express = require('express')

DEPSTAR(CE) 13
CE377: Advanced Web Technology 19DCE061

const dotenv = require('dotenv').config();


const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const path = require('path');
const bodyParser = require('body-parser');
const exhb = require('express-handlebars');
const app = express();
app.engine('hbs', exhb({ extname: 'hbs', defaultLayout: "main", }))
app.set('view engine', 'hbs');
app.set("views", path.join(__dirname, "views"));
app.set("layouts", path.join(__dirname, "views", "layout"));
app.use(bodyParser.urlencoded({ extended: false }))
let i = 4;
app.use(bodyParser.json())
let con = mongoose.connect(process.env.DB_URL, (err) => { console.log(err); });
const firstSchema = new Schema({
id: Number,
title: String,
body: String,});
const myModel = mongoose.model("firstModel", firstSchema);
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "show.html"));});
app.get("/form", (req, res) => {
res.sendFile(path.join(__dirname, "public", "form.html"));})
app.get("/opt", (req, res) => {
myModel.find({ id: { $gt: -1 } }).then((data) => { console.log(data); res.send({ "data":
data }); }).catch((err) => { console.log(err); res.send({ "error": err }) });})

DEPSTAR(CE) 14
CE377: Advanced Web Technology 19DCE061

app.post("/data", (req, res) => {


let title1 = req.body.btitle;
let body1 = req.body.bbody;
const inst = new myModel({ id: i++, title: title1, body: body1 });
inst.save();
res.sendFile(path.join(__dirname, "public", "show.html"));});
app.listen(process.env.PORT || 3001, () => { console.log("Running on PORT : " +
process.env.PORT); })

//env
PORT = 3001
DB_URL =
mongodb+srv://<username>:<pwd>@cluster0.5mcit.mongodb.net/<collectionname>?
retryWrites=true&w=majority

//form.html
<!DOCTYPE html>
<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="./style.css">
<script src="./jquery.js"></script>
<script src="./style.js"></script>
<title>Document</title>
<style>
input[type="text"],
textarea,

DEPSTAR(CE) 15
CE377: Advanced Web Technology 19DCE061

select {
font-size: 2rem;
background: black;
color: #FFFFFF;
outline: none;
padding: 10px;
border: white;
min-inline-size: -webkit-fill-available;
border-radius: 2%;}
select {
padding: 10px;
background: black;
color: #FFFFFF;}
.error {
color: red;}
</style>
</head>
<body>
<!-- navar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark px-3 py-2">
<a class="navbar-brand" style="font-size:xxx-large;" href="/">EmployeeSystem</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">

DEPSTAR(CE) 16
CE377: Advanced Web Technology 19DCE061

<li class="nav-item active">


<a class="nav-link" style="font-size:x-large;" href="/show'; ?>">Show</a>
</li>
</ul>
</div>
</nav>
<!-- navar Ended -->
<!-- Insert Page -->
<div class="container bg-dark text-white p-3">
<center>
<h1 style="font-size:5rem">Form</h1>
</center>
<form action="/data" class="form px-3" method="post">
<h2>Title</h2> <input type="text" name="btitle" placeholder="Enter Title " id="btitle"
required><br>
<br>
<h2>Data</h2>
<textarea name="bbody" id="bbody" cols="30" rows="10" placeholder="Enter
Content"></textarea>
<br>
<br><br>
<input type="submit" class="btn btn-success" value="Submit">&nbsp;<input type="reset"
class="btn btn-danger"
value="Reset">
</form>
</div>
<!-- Insert Page Ended -->
</body>
</html>

DEPSTAR(CE) 17
CE377: Advanced Web Technology 19DCE061

//show.html
<!DOCTYPE html>
<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="./style.css">
<title>Show Data</title>
</head>
<body>
<div class="container">
<!-- <div style="width: 100%;height: 50px;" class="mt-3">
</div> -->
<div id=gvlist class=row>
<div class='col-3 my-3'>
<div class=card style=width:18rem;>
<div class=card-body>
<p>Id:</p>
<script>
var datas;
window.onload = () => { fetch("http://localhost:3001/opt").then((data) =>
{ data.json().then((data) => { datas = data; console.log(data) }).catch((err) =>
console.log(err)) })}
setTimeout(() => {
var datas1 = datas["data"];
datas1.forEach(datas1 => {

DEPSTAR(CE) 18
CE377: Advanced Web Technology 19DCE061

document.write("<h1>Title</h1><h5 class=card-title>" + datas1['title'] +


"</h5><br><h1>Content</h1><h5 class=card-body>" + datas1['body'] + "</h5><hr>")
});}, 2000);</script>
<br><br>
</div></div></div>
</div>
</body></html>

Output:

Practical – 6
Aim: Create user management application using NodeJS and MySql /
MongoDB.
Program Code:
//.env file
PORT=3000

DEPSTAR(CE) 19
CE377: Advanced Web Technology 19DCE061

DB_URL = mongodb+srv://<uname>:<pwd>@cluster0.5mcit.mongodb.net/<databaseName>?
retryWrites=true&w=majority
//index.js
require('dotenv').config();
const express = require('express')
const handlebars = require('express-handlebars')
const path = require('path')
const bodyparser = require('body-parser');
const userschema = require('./userschema');
const mongoose = require('mongoose');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const app = express()
let errs;
app.engine('.hbs', handlebars({
extname: '.hbs', layoutsDir: __dirname + "/views/layout", partialsDir: __dirname +
"/views/partials", helpers: {
list: function (value, options) {
if (value === null)
{return options.fn({ err: "No User Found" });}
return options.fn({ fname: value[0].firstname, lname: value[0].lastname, uname:
value[0].username, email: value[0].email, password: value[0].password, action: "/updateOne/" +
value[0].username, errs: value.err });
}}}));
app.set('view engine', 'hbs');
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
var sessions;
app.use(session({ resave: true, secret: '123456', saveUninitialized: true }));
app.use(cookieParser());

DEPSTAR(CE) 20
CE377: Advanced Web Technology 19DCE061

app.use(express.static(__dirname + "/public"));
mongoose.connect(process.env.DB_URL).then((data)=>console.log(data)).catch(err=>console.lo
g(err))
app.get("/", (req, res) => {res.render('login', { layout: 'main', "err": req.query.err });})
app.get('/form', (req, res) => {res.render("form", { "layout": "main", });});
app.post('/save', (req, res) => {
if (req.session.firstName === undefined || req.session.firstName === null)
res.redirect("/?err=please login first");
else if ((req.session.firstName).localeCompare(sessions) == 0) {
userschema.find({username:req.body.username},(err,reslt)=>{
if(err) res.sendStatus(403).json(err);
else{
if(reslt.length>0)
{res.render("form",{layout:"main","err":"Username Already Occupied"})}
else{
new userschema(req.body).save().then(() => { console.log("Done Saved"); res.redirect("/show");
}).catch((err) => {
if (err) res.sendStatus(405).json(err);});}}});}
else res.redirect("/?err=please login first");});
app.get('/show', (req, res) => {
if (req.session.firstName === undefined || req.session.firstName === null)
res.redirect("/?err=please login first");
else if ((req.session.firstName).localeCompare(sessions) == 0)
userschema.find().then((data) => { res.render('show', { 'layout': 'showing', "data":
data }) }).catch((err) => { console.log(err); });
else res.redirect("/?err=please login first");})
app.post('/login', (req, res) => {
userschema.findOne({ username: req.body.username }).then(
(data) => {

DEPSTAR(CE) 21
CE377: Advanced Web Technology 19DCE061

if (!data)
res.redirect('/?err=No User Found');
let pwd = data.password;
if (pwd.localeCompare(req.body.password) == 0) {sessions =
req.body.username;req.session.firstName = req.body.username;res.redirect('/show');}
else {res.redirect('/?err=Password mismatch');}
}).catch((err) => console.log(err))})
app.get('/logout', (req, res) => {sessions = "";req.session.destroy((err) =>
{res.send(err);});res.redirect('/');})
app.listen(process.env.port || 5000, () => console.log("App is running on " + process.env.port ||
5000));

//userschema.js
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
firstname: {type: String,required: true},
lastname: {type: String,required: true},
username: {type: String,unique: true},
email:{type: String,required: true},
password:{type:String,required:true}})
module.exports = mongoose.model("userModel",userSchema);

//main layout
<!DOCTYPE html>
<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">

DEPSTAR(CE) 22
CE377: Advanced Web Technology 19DCE061

<title>Document</title>
<link rel="stylesheet" href="../bootstrap.css">
<script src="../jquery.js"></script>
<script src="../bootstrap.js"></script>
<style>nav{width: 100%;height: 100%;}
.main{
padding: 20px;}
</style>
</head>
<body>
{{> navbar1}}
<div class="main">
{{{body}}}
</div>
</body>
</html>

//show layout
<!DOCTYPE html>
<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">
<title>Document</title>
<link rel="stylesheet" href="bootstrap.css">
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

DEPSTAR(CE) 23
CE377: Advanced Web Technology 19DCE061

</head>
<body>
{{> navbar1}}
{{{body}}}
</body>
</html>

//navbar partials
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-
target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">Home</a>
</li>
</ul>
</div>
</div>
</nav>

//form.hbs views
{{#if err}}

DEPSTAR(CE) 24
CE377: Advanced Web Technology 19DCE061

<div class="alert alert-danger d-flex align-items-center alert-dismissible fade show"


role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-
label="Danger:"><use xlink:href="#exclamation-triangle-fill"/></svg>
<div>
{{err}} GO to <a href="/form">Create Page</a>
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{else}}
<form class="row g-3 needs-validation" method="POST" action="/save" novalidate>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Firstname</label>
<input type="text" class="form-control" name="firstname" id="validationCustom01"
placeholder="Enter Firstname" required>
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Lastname</label>
<input type="text" class="form-control" name="lastname" id="validationCustom01"
placeholder="Enter Lastname" required>
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Username</label>
<input type="text" class="form-control" name="username" id="validationCustom01"
placeholder="Enter Username" required>
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Email</label>
<input type="email" class="form-control" name="email" id="validationCustom01"
placeholder="Enter Email" required>

DEPSTAR(CE) 25
CE377: Advanced Web Technology 19DCE061

</div>
<div class="row-md-4">
<label for="validationCustom02" class="form-label">Password</label>
<input type="text" class="form-control" name="password" id="validationCustom02"
placeholder="Enter password" required>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Agree to terms and conditions
</label>
</div>
</div>
<a href="/" class="link-primary">Already User</a>
<div class="col-12">
<button class="btn btn-primary pl-2 pr-2" type="submit">Submit</button>
</div>
</form>
{{/if}}

//login.hbs view
{{#if err}}
<div class="alert alert-danger d-flex align-items-center alert-dismissible fade show"
role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg>
<div>

DEPSTAR(CE) 26
CE377: Advanced Web Technology 19DCE061

{{err}}
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{/if}}
<form class="row g-3 needs-validation" method="POST" action="/login" novalidate>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Username</label>
<input type="text" class="form-control" name="username" id="validationCustom01"
placeholder="Enter Username"
required>
</div>
<div class="row-md-4">
<label for="validationCustom02" class="form-label">Password</label>
<input type="text" class="form-control" name="password" id="validationCustom02"
placeholder="Enter password"
required>
</div>
<a href="/form" class="link-primary">New User</a>
<div class="col-12">
<button class="btn btn-primary pl-2 pr-2" type="submit">Submit</button>
</div>
</form>

//show.hbs view
<div class="row">
{{#each data}}
<div class="card col-sm-3 m-2" style="width: 18rem;">
<div class="card-body">

DEPSTAR(CE) 27
CE377: Advanced Web Technology 19DCE061

{{#each this}}
{{#if firstname}}<h5 class="card-title">{{firstname}}{{/if}}
{{#if lastname}}&nbsp;{{lastname}}</h5> {{/if}}
{{/each}}</div></div>
{{/each}}
</div>

Output:

DEPSTAR(CE) 28
CE377: Advanced Web Technology 19DCE061

Practical – 7
Aim: Add Update and delete functionality in Practical 6.
Program Code:
//userschema.js
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
firstname: {type: String,required: true},
lastname: {type: String,required: true},
username: {type: String,unique: true},
email:{type: String,required: true},
password:{type:String,required:true}
})
module.exports = mongoose.model("userModel",userSchema);

DEPSTAR(CE) 29
CE377: Advanced Web Technology 19DCE061

//index.js for update and delete part only


app.get('/update/:username', (req, res) => {
if (req.session.firstName === undefined || req.session.firstName === null) {res.redirect("/?
err=please login first");}
else if ((req.session.firstName).localeCompare(sessions) == 0) {
userschema.find({ username: req.params.username }, (err, reslt) => {
if (err) {res.sendStatus(402).json(err);}
else {if (reslt.length > 0) {reslt.err = errs;errs = "";console.log(reslt + " " + typeof
reslt);res.render("update", { "layout": "main", "data": reslt })}
else {res.render("update", { "layout": "main", "data":null });}}})}})
app.post("/updateOne/:username", (req, res) => {
if (req.session.firstName === undefined || req.session.firstName === null)
res.redirect("/?err=please login first");

else if ((req.session.firstName).localeCompare(sessions) == 0) {
if ((req.body.username).localeCompare(req.params.username) == 0) {
userschema.findOneAndUpdate({ username: req.params.username }, {
$set: {firstname: req.body.firstname,lastname: req.body.lastname,username:
req.body.username,email: req.body.email,password: req.body.password}
}).then((data) => { console.log(data); res.redirect('/show') })
.catch((err) => { console.log(err); })}
else {
userschema.findOne({ username: req.body.username }).then((data) => {
if (data) {errs = "Username Already Occupied";res.redirect("/update/" + req.params.username);}
else {userschema.findOneAndUpdate({ username: req.params.username }, {
$set: { firstname: req.body.firstname, lastname: req.body.lastname, username:
req.body.username, email: req.body.email, password: req.body.password}
}).then((data) => { console.log(data); res.redirect('/show') })
.catch((err) => { console.log(err); })}})}}
else res.redirect("/?err=please login first");})

DEPSTAR(CE) 30
CE377: Advanced Web Technology 19DCE061

app.get('/delete/:username', (req, res) => {


if (req.session.firstName === undefined || req.session.firstName === null)
res.redirect("/?err=please login first");
else if ((req.session.firstName).localeCompare(sessions) == 0) {
userschema.deleteOne({ username: req.params.username }).then((data) =>
{res.redirect('/show');}).catch((err) => {res.send(401).statusMessage(err);})}
else res.redirect("/?err=please login first");})

//update.hbs view
{{#list data}}
{{#if errs}}
<div class="alert alert-danger d-flex align-items-center alert-dismissible fade show"
role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" /></svg>
<div>{{errs}} </div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{/if}}
{{#if err}}
<div class="alert alert-danger d-flex align-items-center alert-dismissible fade show"
role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg>
<div>{{err}} <a href=' / '>Go to Homepage</a></div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{else}}

DEPSTAR(CE) 31
CE377: Advanced Web Technology 19DCE061

<form class="row g-3 needs-validation" method="POST" action={{action}} novalidate>


<div class="row-md-4">
<label for="validationCustom01" class="form-label">Firstname</label>
{{#if fname}}
<input type="text" class="form-control" name="firstname" id="validationCustom01"
placeholder="Enter Firstname"
value={{fname}} required>
{{else}}
<input type="text" class="form-control" name="firstname" id="validationCustom01"
placeholder="Enter Firstname"
required>
{{/if}}
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Lastname</label>
{{#if lname}}
<input type="text" class="form-control" name="lastname" id="validationCustom01"
placeholder="Enter Lastname"
value={{lname}} required>
{{else}}
<input type="text" class="form-control" name="lastname" id="validationCustom01"
placeholder="Enter Lastname"
required>
{{/if}}
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Username</label>
{{#if uname}}
<input type="text" class="form-control" name="username" id="validationCustom01"
onchange="fun()" placeholder="Enter Username"

DEPSTAR(CE) 32
CE377: Advanced Web Technology 19DCE061

value={{uname}} required>
{{else}}
<input type="text" class="form-control" name="username" id="validationCustom01"
placeholder="Enter Username"
required>
{{/if}}
<script>function fun(e){console.log(e.target.value);}</script>
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Email</label>
{{#if email}}
<input type="email" class="form-control" name="email" id="validationCustom01"
placeholder="Enter Email"
value={{email}} required>
{{else}}
<input type="email" class="form-control" name="email" id="validationCustom01"
placeholder="Enter Email" required>
{{/if}}
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Password</label>
{{#if password}}
<input type="text" class="form-control" name="password" id="validationCustom01"
placeholder="Enter Password"
value={{password}} required>
{{else}}
<input type="text" class="form-control" name="password" id="validationCustom01"
placeholder="Enter Password"
required>
{{/if}}

DEPSTAR(CE) 33
CE377: Advanced Web Technology 19DCE061

</div>
<div class="col-12">
<button class="btn btn-primary pl-2 pr-2" type="submit">Submit</button>
</div>
</form>
{{/if}}
{{/list}}
//show.hbs
<div class="row">
{{#each data}}
<div class="card col-sm-3 m-2" style="width: 18rem;">
<div class="card-body">
{{#each this}}
{{#if firstname}}<h5 class="card-title">{{firstname}}{{/if}}
{{#if lastname}}&nbsp;{{lastname}}</h5> {{/if}}
{{#if username}}<p class="card-text">{{username}}</p> <a href=/update/{{username}}
class="btn btn-primary">update</a><a href=/delete/{{username}} class="btn btn-
danger">delete</a>{{/if}}
{{/each}}</div></div>
{{/each}}
</div>

Output:

DEPSTAR(CE) 34
CE377: Advanced Web Technology 19DCE061

Practical – 8
Aim: Create Task management APP using MongoDB and Promises.
Program Code:
//.env file
PORT=3000
DB_URL = mongodb+srv://<uname>:<pwd>@cluster0.5mcit.mongodb.net/<databaseName>?
retryWrites=true&w=majority

//index.js
require('dotenv').config()
const express = require('express')
const handlebars = require('express-handlebars')
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const taskSchema = require('./taskSchema');
const { urlencoded } = require('body-parser');
const flash = require('express-flash');
const app = express()
app.engine('.hbs', handlebars({

DEPSTAR(CE) 35
CE377: Advanced Web Technology 19DCE061

extname: '.hbs', defaultLayout: "main", layoutsDir: __dirname + "/views/layout", partialsDir:


__dirname + "/views/partials", helpers: {
concat: function (value, options) {return options.fn({ update: "/update/" + value._id, delete:
"/delete/" + value._id })},
inc: function (value, options) {return options.fn({ ind: parseInt(value) + 1 })},
itr: function (value, options) {return options.fn({ id: value._id, title: value.title, body:
value.data });}
}}))
app.set('view engine', 'hbs');
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
app.use(express.static(__dirname + "/public"));
mongoose.connect(process.env.DB_URL).then((data) => { console.log("Connected To Db " +
data); }).catch(err => console.log(err))
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');next();});
app.get('/createTask', auth, (req, res) => {
res.render("index", { success: req.flash('success'), err: req.flash('err') })})
app.post('/save', (req, res) => {
new taskSchema({title: req.body.title, data: req.body.data }).save().then((data) =>
{ req.flash("success", "Task Added Successfully"); res.redirect("/show"); }).catch((err) =>
{ console.log(err); throw new Error(err) });})
app.get('/show', auth, (req, res) => {
taskSchema.find().then((data) => {
res.render('show', { "data": data, "err": req.flash("err"), "success": req.flash("success"), "user":
req.user })}).catch((err) => { console.log(err); });})
app.get("/update/:ids", auth, (req, res, next) => {
if (!mongoose.Types.ObjectId.isValid(req.params.ids)) {req.flash("err", "Please Enter valid
ObjectI");res.redirect('/show');}
else {
taskSchema.findById(req.params.ids, (err, data) => {

DEPSTAR(CE) 36
CE377: Advanced Web Technology 19DCE061

if (err) {
res.render("update", { "err": "Internal Database Error" });throw new Error(err);}
else {
if (!data) {res.render("update", { "err": "No User Found" });}
else {res.render("update", { "data": data });}}})}})
app.post("/updateIt", auth, (req, res, next) => {
if (!mongoose.Types.ObjectId.isValid(req.body.id)) {req.flash("err", "Please Enter valid
ObjectI");res.redirect('/show');}
else {
taskSchema.findById(req.body.id, (err, data) => {
if (err) {res.render("update", { "err": "Internal Database Error" });throw new Error(err);}
else {
if (!data) {res.render("update", { "err": "No User Found" });}
else {
taskSchema.findByIdAndUpdate(req.body.id, {
$set: {title: req.body.title,data: req.body.data,}
}).then((data) => { console.log(data); req.flash("success", "Task Updated SuccesssFully");
res.redirect('/show') })
.catch((err) => { res.render("update", { "err": "Internal Database Error" }); throw new Error(err);
})}}})}})
app.get("/delete/:ids", auth, (req, res, next) => {
if (!mongoose.Types.ObjectId.isValid(req.params.ids)) {req.flash("err", "Please Enter valid
ObjectI");res.redirect('/show');}
else {
taskSchema.findById(req.params.ids, (err, data) => {
if (err) {req.flash("err", "Internal Database Error");res.redirect("show");throw new Error(err);}
else {
if (!data) {req.flash("err", "No User Found");res.redirect("show");}
else {
taskSchema.findByIdAndDelete(req.params.ids, (err, data) => {

DEPSTAR(CE) 37
CE377: Advanced Web Technology 19DCE061

if (err) {req.flash("err", "Internal Database Error");res.redirect("show");throw new Error(err);}


else{req.flash("err", "Task Deleted Successfully");res.redirect("/show");}})}}})}})
process.on('uncaughtException', err => {console.log("Err " + err.message);process.exit(1);})
const port = process.env.PORT || 5000;
app.listen(port, () => {console.log("Running on " + port);});

//taskSchema.js
const mongoose = require('mongoose');
const ObjectId = require('mongodb').ObjectID;
let taskSchema = mongoose.Schema({
User_id:{
type:mongoose.Types.ObjectId,
required:true},
title:{
type:String,
required:true},
data:{
type:String,
required:true}
})
module.exports = mongoose.model('taskModel',taskSchema);

//main layout file


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

DEPSTAR(CE) 38
CE377: Advanced Web Technology 19DCE061

<meta http-equiv="X-UA-Compatible" content="IE=edge">


<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href={{process.env.BASE_URL}}"/bootstrap.css">
<script src={{process.env.BASE_URL}}"/jquery.js"></script>
<script src={{process.env.BASE_URL}}"/bootstrap.js"></script>
<title>Show</title>
</head>
<body>
{{> navbar}}
{{> errors}}
<div class="container bg-dark text-white p-3">
<h1><center>Task Management App</center></h1>
{{{body}}}
</div>
</body>
</html>

//navbar partials
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-
target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">

DEPSTAR(CE) 39
CE377: Advanced Web Technology 19DCE061

<a class="nav-link active" aria-current="page" href="/">Home</a>


</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/createTask">Create</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/show">Show</a>
</li>
</ul>
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="/logout">Logout</a>
</li>
</ul>
</div>
</div>
</nav>

//error partials
{{#if success}}
<div class="alert alert-success d-flex align-items-center alert-dismissible fade show"
role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg>
<div>{{success}}</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

DEPSTAR(CE) 40
CE377: Advanced Web Technology 19DCE061

{{/if}}
{{#if err}}
<div class="alert alert-danger d-flex align-items-center alert-dismissible fade show"
role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg><div>{{err}}</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{/if}}

//index.hbs view
<div class="container">
<form class="row g-3 needs-validation" method="POST" action="/save" novalidate>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Enter Your Task Title</label>
<input type="text" class="form-control" name="title" id="validationCustom01"
placeholder="Enter Your Task Title" required></div>
<div class="mb-3">
<label for="validationTextarea" class="form-label">Enter Your Task</label>
<textarea name="data" class="form-control" id="validationTextarea" placeholder="Enter Your
Task"
required></textarea></div>
<div class="col-12">
<button class="btn btn-primary pl-2 pr-2" type="submit" id="submit">Submit</button>
</div></form></div>

//show.hbs view
<div class="container">

DEPSTAR(CE) 41
CE377: Advanced Web Technology 19DCE061

<br><br>
<div class="display">
<table class="table table-stripped table-bordered table-dark">
<thead>
<tr><th scope="col-lg-2">No</th><th scope="col-lg-4">Title</th><th scope="col-lg-
4">Body</th><th scope="col-lg-2"></th></tr>
</thead>
<tbody>
{{#if data}} {{#each data}}
<tr>
{{#inc @index}}<th scope="row">{{ind}}</th>{{/inc}}
{{#each this}}
{{#if title}}<td>{{title}}</td>{{/if}}
{{#if data}} <td>{{data}}</td>{{/if}}{{/each}}
{{#concat this}}
<td><a href={{update}} class="btn btn-primary m-1">Update</a>&nbsp;
<a href={{delete}} class="btn btn-danger m-1" >Delete</a></td>
{{/concat}}
</tr>{{/each}}{{else}}<h1>No Record Found</h1>{{/if}}
</tbody></table></div></div>

//update.hbs view
{{#if err}}
{{else}}
<div class="container">
<form class="row g-3 needs-validation" method="POST" action="/updateIt" novalidate>
<div class="row-md-4">
{{#itr data}}

DEPSTAR(CE) 42
CE377: Advanced Web Technology 19DCE061

{{#if id}}<input type="hidden" name="id" value={{id}}>{{/if}}


<label for="validationCustom01" class="form-label">Enter Your Task Title</label>
{{#if title}}
<input type="text" class="form-control" name="title" id="validationCustom01"
placeholder="Enter Your Task Title" value="{{title}}" required>
{{/if}}
</div>
<div class="mb-3">
{{#if body}}
<label for="validationTextarea" class="form-label">Enter Your Task</label>
<textarea name="data" class="form-control" id="validationTextarea" placeholder="Enter Your
Task"
required>{{body}}</textarea>
{{/if}}
</div>
{{/itr}}
<div class="col-12"><button class="btn btn-primary pl-2 pr-2" type="submit"
id="submit">Submit</button></div>
</form>
</div>
{{/if}}

Output:

DEPSTAR(CE) 43
CE377: Advanced Web Technology 19DCE061

DEPSTAR(CE) 44
CE377: Advanced Web Technology 19DCE061

Practical – 9
Aim: Create REST API with Passport Authentication for practical 8.
Program Code:
//index.js
require('dotenv').config()
const express = require('express')
const handlebars = require('express-handlebars')
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const taskSchema = require('./taskSchema');
const userschema = require('./userschema');
const passport = require('passport')
const { urlencoded } = require('body-parser');
const LocalStrategy = require('passport-local').Strategy;
const flash = require('express-flash');
const app = express()
app.use(flash())
app.engine('.hbs', handlebars({
extname: '.hbs', defaultLayout: "main", layoutsDir: __dirname + "/views/layout", partialsDir:
__dirname + "/views/partials", helpers: {
concat: function (value, options) {return options.fn({ update: "/update/" + value._id, delete:
"/delete/" + value._id })},
inc: function (value, options) {return options.fn({ ind: parseInt(value) + 1 })},
itr: function (value, options) {return options.fn({ id: value._id, title: value.title, body:
value.data });}
}}))
app.set('view engine', 'hbs');
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())

DEPSTAR(CE) 45
CE377: Advanced Web Technology 19DCE061

app.use(express.static(__dirname + "/public"));
mongoose.connect(process.env.DB_URL).then((data) => { console.log("Connected To Db " +
data); }).catch(err => console.log(err))
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');next();});
passport.use(
new LocalStrategy({ usernameField: 'username' }, (username, password, done) => {
userschema.findOne({username: username}).then(user => {
if (!user) {return done(null, false, { message: 'That Username is not registered' });}
if (password.localeCompare(user.password) == 0) {return done(null, user);} else {
return done(null, false, { message: 'Password incorrect' });}});}));
passport.serializeUser(function (user, done) {done(null, user.id);});
passport.deserializeUser(function (id, done) {
userschema.findById(id, function (err, user) {done(err, user);});});
function auth(req, res, next) {
if (req.isAuthenticated()) next();
else {req.flash('success_msg', 'Please Login First');res.redirect("/login");}}
app.get('/login', (req, res) => {
if (req.isAuthenticated()) res.redirect('/show');
res.render('login', { message: req.flash('message') });});
app.post('/login', (req, res, next) => {
if (req.isAuthenticated()) res.redirect('/show');
passport.authenticate('local', {successRedirect: '/show',failureRedirect: '/login',})(req, res,
next);});
app.get('/', passport.authenticate('local', { successRedirect: "/show", failureRedirect: '/login' }))

DEPSTAR(CE) 46
CE377: Advanced Web Technology 19DCE061

app.get('/form', (req, res) => {res.render("register", { success: req.flash('success'), err:


req.flash('err') });});
//username post route requires params username
app.post("/register", (req, res) => {
if (req.isAuthenticated())
res.redirect('/show');
userschema.find({ username: req.body.username }, (err, reslt) => {
if (err) {req.flash('err', err);res.redirect("/register");}
else {
if (reslt.length > 0) {
req.flash('err', "Username Already Occupied");res.redirect("/form");}
else {
new userschema(req.body).save().then(() => { console.log("Done Saved"); res.redirect("/show");
}).catch((err) => {
if (err) {req.flash('err', err);res.redirect("/form");}});}}});
})
app.get('/createTask', auth, (req, res) => {
res.render("index", { success: req.flash('success'), err: req.flash('err') })})
app.post('/save', (req, res) => {
if (req.isAuthenticated())
res.redirect('/show');
new taskSchema({ User_id: req.user.id, title: req.body.title, data:
req.body.data }).save().then((data) => { req.flash("success", "Task Added Successfully");
res.redirect("/show"); }).catch((err) => { console.log(err); throw new Error(err) });})
app.get('/show', auth, (req, res) => {
taskSchema.find({ 'User_id': req.user.id }).then((data) => {
res.render('show', { "data": data, "err": req.flash("err"), "success": req.flash("success"), "user":
req.user })
}).catch((err) => { console.log(err); });})
app.get("/update/:ids", auth, (req, res, next) => {

DEPSTAR(CE) 47
CE377: Advanced Web Technology 19DCE061

if (!mongoose.Types.ObjectId.isValid(req.params.ids)) {req.flash("err", "Please Enter valid


ObjectI");res.redirect('/show');}
else {
taskSchema.findById(req.params.ids, (err, data) => {
if (err) {
res.render("update", { "err": "Internal Database Error" });throw new Error(err);}
else {
if (!data) {res.render("update", { "err": "No User Found" });}
else {res.render("update", { "data": data });}}})}})
app.post("/updateIt", auth, (req, res, next) => {
if (!mongoose.Types.ObjectId.isValid(req.body.id)) {req.flash("err", "Please Enter valid
ObjectI");res.redirect('/show');}
else {
taskSchema.findById(req.body.id, (err, data) => {
if (err) {res.render("update", { "err": "Internal Database Error" });throw new Error(err);}
else {
if (!data) {res.render("update", { "err": "No User Found" });}
else {
taskSchema.findByIdAndUpdate(req.body.id, {
$set: {title: req.body.title,data: req.body.data,}
}).then((data) => { console.log(data); req.flash("success", "Task Updated SuccesssFully");
res.redirect('/show') })
.catch((err) => { res.render("update", { "err": "Internal Database Error" }); throw new Error(err);
})}}})}})
app.get("/delete/:ids", auth, (req, res, next) => {
if (!mongoose.Types.ObjectId.isValid(req.params.ids)) {req.flash("err", "Please Enter valid
ObjectI");res.redirect('/show');}
else {
taskSchema.findById(req.params.ids, (err, data) => {
if (err) {req.flash("err", "Internal Database Error");res.redirect("show");throw new Error(err);}

DEPSTAR(CE) 48
CE377: Advanced Web Technology 19DCE061

else {
if (!data) {req.flash("err", "No User Found");res.redirect("show");}
else {
taskSchema.findByIdAndDelete(req.params.ids, (err, data) => {
if (err) {req.flash("err", "Internal Database Error");res.redirect("show");throw new Error(err);}
else{req.flash("err", "Task Deleted Successfully");res.redirect("/show");}})}}})}})
app.get('/logout', function (req, res, next) {req.logout();req.flash('success', 'You are logged
out');res.redirect('/login');});
process.on('uncaughtException', err => {console.log("Err " + err.message);process.exit(1);})
const port = process.env.PORT || 5000;
app.listen(port, () => {console.log("Running on " + port);});

//taskschema.js
const mongoose = require('mongoose');
const ObjectId = require('mongodb').ObjectID;
let taskSchema = mongoose.Schema({
User_id:{
type:mongoose.Types.ObjectId,
required:true},
title:{
type:String,
required:true},
data:{
type:String,
required:true}})
module.exports = mongoose.model('taskModel',taskSchema);

//userschema.js

DEPSTAR(CE) 49
CE377: Advanced Web Technology 19DCE061

const mongoose = require("mongoose");


const userSchema = mongoose.Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true},
username: {
type: String,
unique: true
},
email:{
type: String,
required: true
},
password:{
type:String,
required:true}
}
);
module.exports = mongoose.model("userModel",userSchema);

//login.hbs view
<form class="row g-3 needs-validation" method="POST" action="/login" novalidate>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Username</label>

DEPSTAR(CE) 50
CE377: Advanced Web Technology 19DCE061

<input type="text" class="form-control" name="username" id="validationCustom01"


placeholder="Enter Username"
required></div>
<div class="row-md-4">
<label for="validationCustom02" class="form-label">Password</label>
<input type="text" class="form-control" name="password" id="validationCustom02"
placeholder="Enter password"
required></div>
<a href="/form" class="link-primary">New User</a>
<div class="col-12"><button class="btn btn-primary pl-2 pr-2"
type="submit">Submit</button></div>
</form>

//register.hbs view
{{#if err}}
{{else}}
<form class="row g-3 needs-validation" method="POST" action="/register" novalidate>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Firstname</label>
<input type="text" class="form-control" name="firstname" id="validationCustom01"
placeholder="Enter Firstname" required>
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Lastname</label>
<input type="text" class="form-control" name="lastname" id="validationCustom01"
placeholder="Enter Lastname" required>
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Username</label>

DEPSTAR(CE) 51
CE377: Advanced Web Technology 19DCE061

<input type="text" class="form-control" name="username" id="validationCustom01"


placeholder="Enter Username" required>
</div>
<div class="row-md-4">
<label for="validationCustom01" class="form-label">Email</label>
<input type="email" class="form-control" name="email" id="validationCustom01"
placeholder="Enter Email" required>
</div>
<div class="row-md-4">
<label for="validationCustom02" class="form-label">Password</label>
<input type="text" class="form-control" name="password" id="validationCustom02"
placeholder="Enter password" required>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Agree to terms and conditions
</label>
</div>
<a href="/" class="link-primary">Already User</a>
<div class="col-12">
<button class="btn btn-primary pl-2 pr-2" type="submit">Submit</button>
</div>
</form>
{{/if}}

Output:

DEPSTAR(CE) 52
CE377: Advanced Web Technology 19DCE061

Practical – 10
Aim: Add Sorting, Pagination, and Filtering functionality to Practical 8.

DEPSTAR(CE) 53
CE377: Advanced Web Technology 19DCE061

Program Code:
//index.js
const pagination = require('./pagination')
app.use("/showPage",pagination);

//Pagination.js
const { urlencoded } = require('body-parser');
const Router = require('express');
const express = require('express');
const taskSchema = require('./taskSchema');
const app = Router();
app.get('/',(req,res)=>{
taskSchema.find({ 'User_id': "614e1a40e96c3816e3d10afc"}).limit(5).exec(
(err,data)=>{
res.render('showPage',{"layout":"empty","data":data})} )
}).get('/:nums',(req,res)=>{
let pageSkip = req.params.nums;
taskSchema.find({ 'User_id':
"614e1a40e96c3816e3d10afc"}).skip(parseInt(pageSkip)).limit(5).exec(
(err,data)=>{
data.forEach((Element,index)=>{
Element.__v = index;})
console.log(data);
res.json(data) })
}).get("/sort/asc",(req,res)=>{
taskSchema.find({ 'User_id': "614e1a40e96c3816e3d10afc"}).limit(5).sort({"_id":-1}).exec(
(err,data)=>{
data.forEach((Element,index)=>{

DEPSTAR(CE) 54
CE377: Advanced Web Technology 19DCE061

Element.__v = index; })
res.json(data) })
}).get("/sort/dsc",(req,res)=>{
taskSchema.find({ 'User_id': "614e1a40e96c3816e3d10afc"}).limit(5).sort({"_id":1}).exec(
(err,data)=>{
data.forEach((Element,index)=>{
Element.__v = index; })
res.json(data) })
}).get("/filter/:title",(req,res)=>{
taskSchema.find({ 'User_id':
"614e1a40e96c3816e3d10afc","title":RegExp(req.params.title,"i")}).limit(5).exec(
(err,data)=>{
data.forEach((Element,index)=>{
Element.__v = index; })
res.json(data) })});
module.exports = app;

//show.hbs
<div class="cst" id="cst">
</div>
<div class="container m-1 p-1">
<button id='p-p-2' class="btn btn-primary">For Previous Page</button>
<button id='n-p-2' class="btn btn-primary">For Next Page</button>
<button id='asc' class="btn btn-primary">For Sort Ascending</button>
<button id='dsc' class="btn btn-primary">For Sort Descending</button>
<button id='filter' class="btn btn-primary">For Filter</button>
</div>
<script>

DEPSTAR(CE) 55
CE377: Advanced Web Technology 19DCE061

function getTable(data) {
let trs = document.querySelectorAll(".bdy");
let tbody = document.querySelector("tbody");
trs.forEach((Element) => { Element.remove() });
for (var i = 0; i < data.length; i++) {
let tr = document.createElement("tr");
tr.setAttribute("class", "bdy");
let no = document.createElement("td");
no.innerHTML = i + 1;
let title = document.createElement("td");
title.innerHTML = data[i]['title'];
let body = document.createElement("td");
body.innerHTML = data[i]['data'];
let btn = document.createElement("td");
let update = document.createElement("a");
update.setAttribute('class', "btn btn-primary m-1");
update.innerText = "Update";
update.setAttribute('href', "/update/" + data[i]["_id"]);
let deletes = document.createElement("a");
deletes.setAttribute('href', "/delete/" + data[i]["_id"]);
deletes.setAttribute('class', "btn btn-danger m-1");
deletes.innerText = "Delete";
btn.appendChild(update);
btn.appendChild(deletes);
tr.appendChild(no);
tr.appendChild(title);
tr.appendChild(body);
tr.appendChild(btn);

DEPSTAR(CE) 56
CE377: Advanced Web Technology 19DCE061

tbody.appendChild(tr); }}
function fun(num) {
$.ajax({
url: num == 0 ? 'showPage' : 'showPage/' + num,
method: 'GET',
success: (data) => {
if (num === 0) {
document.getElementById("cst").innerHTML = data; }
else {
console.log("Data length is " + data.length);
if (data.length < 5) {
let row = document.querySelectorAll('tr.bdy');
for (let i = row.length - 1; i >= data.length; i--) {
row[i].remove(); }}
data.forEach((Element, index) => {
console.log("Works for..." + index + Element.data)
if (index <= (data.length - 1)) {
console.log(index + " " + document.querySelectorAll("td.title")[0] + ' ' +
Element.title);
document.querySelectorAll(`td.title`)[parseInt(index)].innerText =
Element.title;
document.querySelectorAll(`td.body`)[parseInt(index)].innerText =
Element.data;
}
else {
console.log("Error ..."); }})
}}})}
function sort(sortType) {
$.ajax({

DEPSTAR(CE) 57
CE377: Advanced Web Technology 19DCE061

url: sortType.localeCompare("asc") ? "showPage/sort/asc" : "showPage/sort/dsc",


method: 'GET',
success: (data) => {
getTable(data); }})}
//For Getting Data on start
window.onload = (e) => {
fun(0) }
document.getElementById("n-p-2").addEventListener('click', (e) => { fun(5) });
document.getElementById("p-p-2").addEventListener('click', (e) => { fun(0) });
document.getElementById("asc").addEventListener('click', (e) => { sort("asc") });
document.getElementById("dsc").addEventListener('click', (e) => { sort("dsc") });
document.getElementById("filter").addEventListener('click', (e) => {
let data = prompt("Enter title for Filtering ");
while (data.toString == "") {
data = prompt("Enter title for Filtering "); }
$.ajax({
url: "showPage/filter/" + data,
method: 'GET',
success: (data) => {
getTable(data); }
})
});
</script>

//showPage.hbs
<!-- Main Started -->
<div class='cnt' id='cnt'>
<div class='container' id='showPagi'>

DEPSTAR(CE) 58
CE377: Advanced Web Technology 19DCE061

<br><br>
<div class='display'>
<table class='table table-stripped table-bordered table-dark'>
<thead>
<tr>
<th scope='col-lg-2'>No</th>
<th scope='col-lg-4'>Title</th>
<th scope='col-lg-4'>Body</th>
<th scope='col-lg-2'></th>
</tr>
</thead>
<tbody>
{{#if data}}
{{#each data}}
<div class="row" id="row">
<tr class="bdy">
{{#inc @index}}
<th scope='row'>{{ind}}</th>
{{/inc}}
{{#itr this}}
{{#if title}}
<td class="title">{{title}}</td>
{{/if}}
{{#if body}}
<td class="body">{{body}}</td>
{{/if}}
{{/itr}}
{{#concat this}}

DEPSTAR(CE) 59
CE377: Advanced Web Technology 19DCE061

<td><a href={{update}} class='btn btn-primary m-1'>Update</a>&nbsp;


<a href={{delete}} class='btn btn-danger m-1'>Delete</a>
</td>
{{/concat}}
</tr>
</div>
{{/each}}
{{else}}
<h1>No Record Found</h1>
{{/if}}
</tbody>
</table>
</div>
</div>
</div>
<!-- Main Ended -->

Output:

DEPSTAR(CE) 60
CE377: Advanced Web Technology 19DCE061

DEPSTAR(CE) 61
CE377: Advanced Web Technology 19DCE061

Practical – 11
Aim: Add Upload File and Send Email utilities to practical 8.
Program Code:
//index.js
const fileEmail = require('./fileEmail');
app.use("/fileEmail",fileEmail);

//fileEmail.js
const Router = require('express');
const express = require('express');
const taskSchema = require('./taskSchema');
var nodemailer = require('nodemailer');
const path = require('path')
const bodyParser = require('body-parser');
const multer = require('multer');
const { log } = require('console');
const storage = multer.diskStorage(
{
destination: function (req, file, cb) {
cb(null, path.join(__dirname,"/public/uploads/"))
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
}
});
var upload = multer({ storage: storage });
const app = Router();
app.use(bodyParser.json());

DEPSTAR(CE) 62
CE377: Advanced Web Technology 19DCE061

app.use(bodyParser.urlencoded({extended:false}))
app.get("/uploadImage",(req,res)=>{
res.render("fileEmail",{"email":"Done"});
}).get('/image/:any',(req,res)=>{
log(path.join(__dirname,"/public","uploads"));
res.sendFile(__dirname+"/public/uploads/"+req.params.any);
}).post('/profile', upload.array("files",1),function (req, res, next) {
try {
log(req.files[0].filename);
// res.send(req.file);
} catch (error) {
log("Error "+error)}
res.render("fileEmail",{"email":{"submitted":"image/"+req.files[0].filename}});
}).get("/email",(req,res)=>{
res.render("fileEmail",{"success":req.flash("Success"),"error":req.flash("error")});
}).post('/sendEmail',(req,res)=>{
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'pass'
}});
var mailOptions = {
from: 'email',
to: req.body.email,
subject: req.body.subject,
text: req.body.msg };
transporter.sendMail(mailOptions, function(error, info){

DEPSTAR(CE) 63
CE377: Advanced Web Technology 19DCE061

if (error) {
console.log(error);
req.flash("error","Email Sent")
res.redirect("./email"); }
else {
console.log('Email sent: ' + info.response);
req.flash("Success","Email Sent")
res.redirect("./email");
}});})
module.exports = app;

//fileEmail.hbs
{{email.submitted}}
{{#if email}}
{{#if email.submitted}}
<img class="card-img-top" src='{{email.submitted}}' style="height:300px;
width:300px;" alt="Card image cap">
{{else}}
<label for="exampleFormControlFile1">Example file input</label>
<form method="POST" action="/fileEmail/profile" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="files">
<br><button class="btn btn-primary">Upload</button>
</div>
</form>{{/if}}
{{else}}
<form action="/fileEmail/sendEmail" method="POST">
<div class="form-group">

DEPSTAR(CE) 64
CE377: Advanced Web Technology 19DCE061

<label for="exampleFormControlInput1">Email address</label>


<input type="email" class="form-control" name="email" id="exampleFormControlInput1"
required placeholder="name@example.com">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Subject</label>
<input type="text" class="form-control" name="subject" id="exampleFormControlInput1"
required placeholder="Enter Subject">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Email Text</label>
<textarea class="form-control" name="msg" id="exampleFormControlTextarea1" rows="3"
required placeholder="Enter Email Text"></textarea></div>
<button class="btn btn-primary">Send</button>
</form>
{{/if}}

Output:

DEPSTAR(CE) 65
CE377: Advanced Web Technology 19DCE061

Practical – 12

DEPSTAR(CE) 66
CE377: Advanced Web Technology 19DCE061

Aim: Create Bookstore (eCommerce) application with payment integration.


Program Code:
//index.js
require('dotenv').config()
const express = require("express");
const flash = require("express-flash");
const path = require("path");
const handlebars = require("express-handlebars");
const session = require('express-session');
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const stripe = require("stripe")("PUB_KEY");
const app = express();
let receipt_url;
app.engine(
"hbs",handlebars({extname:".hbs",defaultLayout:"main",defaultLayout: "main", layoutsDir:
__dirname + "/views/layout", partialsDir: __dirname + "/views/partials"})
);
app.use(cookieParser());
app.use(flash());
app.set('view engine', 'hbs');
app.set('view engine', 'hbs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false,

DEPSTAR(CE) 67
CE377: Advanced Web Technology 19DCE061

cookie: { maxAge: 180*60*1000 }


}));
app.use(express.static(__dirname + "/public"));
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();});
app.get("/",(req,res)=>{
res.render("products",{"title":"Home","data":[
{
"title":"MEAN Web Development",
"short_desc":"The MEAN stack is a collection of the most popular modern tools for web
development;",
"desc":"The MEAN stack is a collection of the most popular modern tools for web development;
it comprises MongoDB, Express, AngularJS, and Node.js.",
"src":"/imgs/MEAN Web Development.jpg",
"curr":"₹",
"price":"250"
},
{
"title":"Pro MEAN Stack Development",
"short_desc":"Master the MEAN stack with this book today",
"desc":"Write free, open-source, cross-platform, dynamic JavaScript applications that can run
anywhere using the MEAN stack - MongoDB, ExpressJS, AngularJS, and Node.js. With this
book Mac developers will get the tools needed to set up, write code once, and be able to deploy
code on any device. You will be able to cut development time by using one stack to serve all
your development needs. Pro MEAN Stack Development enables you to quickly learn
everything needed to work effectively with MEAN, from setting up your toolstack to rolling out
your free servers, and deploying on any device. You will also learn to build scripts with Grunt
and Gulp, Webpack, and Vagrant and how to deploy to the web and mobile using Phonegap.
Harness JavaScript to create dynamic and easily-maintainable applications fast and 100% free.

DEPSTAR(CE) 68
CE377: Advanced Web Technology 19DCE061

Master the MEAN stack with this book today. What You Will Learn Utilize JavaScript for the
entire development cycle from front end to back end, database and deployment. Learn to write
responsive code that can be deployed on any device. Become a well-rounded developer and be
able to understand the entire development cycle. Learn to utilize free open source and cloud
services to deploy production-grade code. Who This Book Is For Front or back end Mac
developers familiar with JavaScript and interested in utilizing the MEAN stack to deploy
successful apps on all devices.",
"src":"/imgs/pro-mean-stack-development.jpeg",
"curr":"₹",
"price":"300"
},
]});});
app.get("/payment/:title/:price",(req,res)=>{
req.session.title = req.params.title;
req.session.price = req.params.price;
res.render("payment",{key:
process.env.PUB_KEY,"url":process.env.BASE_URL,"price":parseInt(req.params.price)*100});
})
app.post("/payment/:title/:price",(req,res)=>{
const info = req.session.title;
const price = req.session.price*100;
stripe.customers.create({
email: req.body.stripeEmail,
source: req.body.stripeToken,
name: 'Gourav Hammad',
address: {
line1: 'TC 9/4 Old MES colony',
postal_code: '452331',
city: 'Indore',
state: 'Madhya Pradesh',
country: 'India',}})

DEPSTAR(CE) 69
CE377: Advanced Web Technology 19DCE061

.then((customer) => {
console.log("C is "+customer.id);
return stripe.charges.create({
amount: price, // Charing Rs 25
description: info,
currency: 'INR',
customer: customer.id}); })
.then((charge) => {
receipt_url = charge.receipt_url;
req.flash("suceess","Payment Done");
res.redirect("/invoice"); // If no error occurs})
.catch((err) => {
console.log(err);
req.flash("err",err.code);// If some error occurs
res.redirect("/invoice"); // If no error occurs
});})
app.get("/invoice",(req,res)=>{
res.render("success",
{"success":req.flash("success"),"err":req.flash("err"),"receipt_url":receipt_url,"url":process.env.
BASE_URL});})
const port = process.env.PORT || 5000;
app.listen(port,()=>{console.log("App is Running on "+port);})

//main.hbs layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

DEPSTAR(CE) 70
CE377: Advanced Web Technology 19DCE061

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<link rel="stylesheet" href="{{{url}}}/bootstrap.css">
<script src="{{{url}}}/jquery.js"></script>
<script src="{{{url}}}/bootstrap.js"></script>
<title>{{title}}</title>
</head>
<body class="d-flex flex-column h-100">
{{>header}}
{{{body}}}
{{>footer}}
</body>
</html>

//footer.hbs partials
<footer class="footer position-fixed bottom-0 py-3 bg-light">
<div class="container">
<span class="text-muted">Copyright From Mine</span>
</div>
</footer>

//header.hbs partials
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Book store</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-
target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button> </div>

DEPSTAR(CE) 71
CE377: Advanced Web Technology 19DCE061

</nav>

//products.hbs view
<div class="row">
{{#each data}}
<div class="col-3">
<div class="card" style="width: 18rem;">
<img src="{{{this.src}}}" style="height:300px;width:auto;" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Title: {{{this.title}}}</h5>
<p class="card-text">Details: {{{this.short_desc}}}</p>
<h5 class="card-title">Price: {{{this.curr}}} {{{this.price}}}</h5>
<a href="/payment/{{{this.title}}}/{{{this.price}}}" class="btn btn-primary">For payment</a>
</div>
</div>
</div>
{{/each}}
</div>

//success.hbs view
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="check-circle-fill" fill="currentColor" viewBox="0 0 16 16">
<path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417
5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0
0-.01-1.05z"/>
</symbol>
<symbol id="info-fill" fill="currentColor" viewBox="0 0 16 16">
<path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194
0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-

DEPSTAR(CE) 72
CE377: Advanced Web Technology 19DCE061

3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1


0 2z"/>
</symbol>
<symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
<path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98
1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35
3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-
2z"/>
</symbol>
</svg>
{{#if success}}
<div class="alert alert-success d-flex align-items-center alert-dismissible fade show"
role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-
label="Success:"><use xlink:href="#check-circle-fill"/></svg>
<div>
{{{success}}}
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{/if}}
{{#if err}}
<div class="alert alert-danger d-flex align-items-center alert-dismissible fade show"
role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-
label="Danger:"><use xlink:href="#exclamation-triangle-fill"/></svg>
<div>
{{{err}}}
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

DEPSTAR(CE) 73
CE377: Advanced Web Technology 19DCE061

{{/if}}
<br>
{{#if url}}
<a href="{{{receipt_url}}}">For Getting invoice</a>
{{/if}}

Output:

DEPSTAR(CE) 74

You might also like