Professional Documents
Culture Documents
Practical – 1
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:
DEPSTAR(CE) 4
CE377: Advanced Web Technology 19DCE061
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.
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"))
DEPSTAR(CE) 6
CE377: Advanced Web Technology 19DCE061
Practical – 3
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") });
DEPSTAR(CE) 8
CE377: Advanced Web Technology 19DCE061
<body>
{{content}}
{{{body}}}
</body>
</html>
Output:
Practical – 4
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
//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}} ℃</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
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
DEPSTAR(CE) 14
CE377: Advanced Web Technology 19DCE061
//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
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
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
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}} {{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
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
//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
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}} {{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
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
//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);
DEPSTAR(CE) 38
CE377: Advanced Web Technology 19DCE061
//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
//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>
<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
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
DEPSTAR(CE) 47
CE377: Advanced Web Technology 19DCE061
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
//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
//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
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
//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
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
Output:
DEPSTAR(CE) 65
CE377: Advanced Web Technology 19DCE061
Practical – 12
DEPSTAR(CE) 66
CE377: Advanced Web Technology 19DCE061
DEPSTAR(CE) 67
CE377: Advanced Web Technology 19DCE061
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
//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
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