School of Information Technology and Engineering (SITE) : HTML Lang Dir Charset

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

School of Information Technology and Engineering [SITE]

Course Title: Web Technology Course Code: ITE1002


Name: Vasanti Vivek Rampurkar Reg no: 20BIT0005
Experiment: 4 Date: 2/12/2021

(1) Consider a client requests the server to view his profile, which is available in “19BIT0-info.html”.
Implement it using the Node.js file system module.

CODE-

20BIT0005_info.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>20BIT0005</title>
</head>
<body>
<h1>Profile</h1>
<p>Name: Vasanti Rampurkar</p>
<p>Reg. no.: 20BIT0005</p>
<p>Branch: Information Technology</p>
<p>Age: 20</p>
<p>Year: 2nd</p>
<p>Semester: 3rd</p>
<p>Subject: Web technologies</p>
</body>
</html>

Q1.js

var http = require('http');


var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile('20BIT0005_info.html', function(err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}).listen(8080);

OUTPUT:

(2) Develop a small application for the Basketball scoreboard using Node.js event handling.Here, we
have a scoreKeeper.on() event-listener listening for an event that would indicate a basket being
made. Each scoring attempt is a call of the shoot_a_basket function. If the ball goes in the net
(indicated by a true value for theshot), scoreKeeper.emit() is called, which alerts all event-listeners
listening for the make_basket event announcement to run their callback function, and passes the
value of the basket made. Display the scores of each team.

Q2.js:

const events = require('events');


const scoreKeeper = new events.EventEmitter();
var teamA = 0;
var teamB = 0;
function make_basket(team) {
if (team === "A") {
teamA += 1;
} else {
teamB += 1;
}
console.log("Score of team A is" + teamA);
console.log("Score of team B is" + teamB);
console.log("--------------------------");
}
scoreKeeper.on('make_basket', make_basket);
function scored(team) {
scoreKeeper.emit('make_basket', team);
}
scored("A");
scored("B");
scored("A");
scored("A");
scored("B");
scored("A");

OUTPUT:

(3) Create a MongoDB “Student” database and do the following operations:

1. Insert a new student with a name: Dora

2. Insert a new student with a name: Sinchan and id=2 (integer)

3. Insert a new student with a name: Angush, the midterm score of 80, and a final score of 100.
Scores should be embedded in a sub-document like this: scores:{midterm:0,final:0}.

4. Finding a document by a single attribute as name as “your name”.

5. Display the list of students who scored between greater than 50 in the midterm.
6. Search for students that have scored between [50,80] in midterm AND [80,100] in the final exam.

7. Update the student Sinchan that you created back in exercise 2 to have a midterm score of 50 and
a final score of 100 respectively.

8. Sort according to the final score in descending order and display name and score without
objectID.

9. Delete user Angush that you created back in exercise 3

10. Delete all users with a midterm score of less than 80.

(4) i) Design an application using node.js and MongoDB to perform the following operations in a
student collection with a name, age, DOB, and year of admission.

ii) Insert multiple records into the collection.

iii) Sort all documents in the student collection

const mongoose = require("mongoose")


mongoose.connect("mongodb://localhost:27017/Class", { useNewUrlParser: true
});
const studentSchema = new mongoose.Schema({
name: String,
age: Number,
dob: Date,
yearofadm: Number
});
const Student = mongoose.model("Student2", studentSchema)
const Vasanti = new Student({
name: "Vasanti",
age: 19,
dob: "2002-05-11",
yearofadm: 2020
});
const Avnatika = new Student({
name: "Avantika",
age: 14,
dob: "2007-02-18",
yearofadm: null
});
const Mahek = new Student({
name: "Dhruvil",
age: 19,
dob: "2002-10-31",
yearofadm: 2020
});
const Akshat = new Student({
name: "Akshat",
age: 26,
dob: "1995-10-15",
yearofadm: 2014
});
const Nandini = new Student({
name: "Nandini",
age: 25,
dob: "1995-05-04",
yearofadm: 2017
});
const Kevin = new Student({
name: "Kevin",
age: 25,
dob: "1995-05-04",
yearofadm: 2017
});
Student.insertMany([Vasanti, Avnatika, Mahek, Akshat, Nandini,Kevin],
function(err) {
if (err) {
console.log(err);
} else {
console.log("successfully saved all the students")
}
});
Student.find(function(err, student) {
if (err) {
console.log(err)
} else {
student.forEach((student) => {
console.log(student.name)
});
}
});

OUTPUT:

iv) Update the document of a student with name=’Kevin’ to age=25

Update the document of a student with name=’Kevin’ to age=25


Student.update({ name: "Kevin" }, { $set: { age: 30 } }, function(err) {
if (err) {
console.log(err)
} else {
console.log('updation completed')
}
})

OUTPUT:

v) Limit the result to 4 documents

Student.find(function(err, student) {
if (err) {
console.log(err)
}
else {
student.forEach((student) => {
console.log(student);
});
}
}).limit(4)

OUTPUT:

vi) Query the document based on age>25

Student.find({ "age": { $gt: 25 } }, function(err, student) {


if (err) {
console.log(err)
}
else {
student.forEach((student) => {
console.log(student);
});
}
})

OUTPUT:

(5) i) Create a web application with username in HTML and node.js using the express framework to
handle different types of HTTP requests namely get, post, put, options, and delete.

ii) Provide different route paths for each of the requests.

iii) Display the different request types with the username in the browser when the application is
executed.

HTML File :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>20BIT0005</title>
</head>
<body>
<h1>For Post Method</h1>
<form action="/post" method="post">
Username: <input name="username" type="text" /> <br />
<input type="submit" value="Submit(Post Request)" />
</form>
<h1>For Get Method</h1>
<form action="/get" method="get">
Username: <input name="username" type="text" /> <br />
<input type="submit" value="Submit(Get Request)" />
</form>
<p>Use postman to see the output of the requests PUT and DELETE</p>
<p>For PUT :- http://127.0.0.1:3000/put/username</p>
<p>For DELETE :- http://127.0.0.1:3000/delete/username</p>
</body>
</html>

Node js:

const express = require("express")


const app = express()
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/20BIT0005_Q5.html');
});
app.get('/get', function(req, res) {
var name = req.query.username;
res.send(name + ' This is Get Request ');
});
app.post('/post', function(req, res) {
var name = req.body.username;
res.send(name + ' This is Post Request ');
});
app.put('/put/:username', function(req, res) {
var name = req.params.username;
res.send(name + ' This is Put Request ');
});
app.delete('/delete/:username', function(req, res) {
var name = req.params.username;
res.send(name + ' This is Delete Request ');
});
app.listen(3000, function() {
console.log("server has started");
});

OUTPUT:
6. i) Write an HTML and node.js program for creating and storing session information of the user.
The HTML page contains username, password, remember me next time checkbox option and a login
button. ii) Assume, the user name and password are already registered in the node.js server. iii)
Perform the following: a. If the user enters an invalid user username or password, display an
appropriate error message. b. After successful login, display a welcome message. c. Allow the user to
enter the username and password for 3 times. If the user enters username and password more than
3 times, display the message “you are blocked”.
CODE:

<html>
<head>
<title>20BIT0005</title>
</head>
<body>
<form action="http://localhost:8081/login" method="GET">
Username: <input type="text" name="username" /> <br /> Password:
<input type="text" name="passwords" /> Remeber Me:<input type="radio"
value="yes" name="remember" /> Yes <input type="radio" value="no"
name="remember" /> No
<input type="submit" value="Submit" />
</form>
</body>
</html>

Node js:

var express = require('express');


var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser());
var session = require('express-session');
app.use(session({
secret: "Shh, its a secret!",
resave: true,
saveUninitialized: true
}));
app.use(express.static('public'));
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
app.get('/', function(req, res) {
if (req.session.rememberme == "yes") {
res.redirect(`/login?username=${req.session.username}&passwords=${req.session.
username}`);
} else {
res.sendFile(__dirname + "/" + "20BIT0005info.html");
}
});
app.get('/login', function(req, res) {
res.cookie("Username", "Vasanti");
res.cookie("Password", "1234");
username = req.query.username;
passwords = req.query.passwords;
remember = req.query.remember;
if (req.cookies['Username'] != username || req.cookies['Password']
!=passwords) {
if (req.session.page_views) {
req.session.page_views++;
} else {
req.session.page_views = 1;
}
}
if (req.session.page_views >= 4)
var k = "<h1>you are blocked</h1>";
else {
if (req.cookies['Username'] == username && req.cookies['Password']==
passwords) {
if (remember == "yes") {
req.session.rememberme = "yes";
} else
req.session.rememberme = "yes";
var k = "<h1>Welcome!</h1>";
} else
var k = "<h1>Wrong!</h1>";
}
res.end(k);
});
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});

OUTPUT:

7. A company database maintains the vehicle information of their employees. It stores the
information empid(int), vehicle number(string/int), owner name(string), brand name(string) and
year of purchase(int). a) Create a Collection in MongoDB with the above fields and insert 10
documents at least.

CODE:

const mongoose = require('mongoose');


mongoose.connect('mongodb://localhost:27017/company', { useNewUrlParser:
true });
const compSchema = new mongoose.Schema({
empid: Number,
vehicalno: String,
owner: String,
brand: String,
year: Number
});
const Employee = mongoose.model("Employee", compSchema)
const bhanu = new Employee({
empid: 1,
vehicalno: "Z101",
owner: "Bhanu",
brand: "xyz",
year: 2018
});
const brand = new Employee({
empid: 2,
vehicalno: "Z145",
owner: "Brand",
brand: "zxy",
year: 2020
});
const anna = new Employee({
empid: 3,
vehicalno: "W456",
owner: "Anna",
brand: "fod",
year: 2018
});
const kamna = new Employee({
empid: 4,
vehicalno: "I108",
owner: "Kamna",
brand: "xyz",
year: 2020
});
const roy = new Employee({
empid: 5,
vehicalno: "R666",
owner: "Roy",
brand: "wor",
year: 2017
});
const jay = new Employee({
empid: 6,
vehicalno: "A101",
owner: "Jay",
brand: "iot",
year: 2014
});
const ishan = new Employee({
empid: 7,
vehicalno: "B546",
owner: "Ishan",
brand: "pqr",
year: 2019
});
const rohit = new Employee({
empid: 8,
vehicalno: "A101",
owner: "Rohit",
brand: "xyz",
year: 2020
});
const bansal = new Employee({
empid: 9,
vehicalno: "WW32",
owner: "bansal",
brand: "iot",
year: 2000
});
const shreya = new Employee({
empid: 10,
vehicalno: "A101",
owner: "Shreya",
brand: "xyz",
year: 2020
});
Employee.insertMany([bhanu, brand, kamna, anna, roy, ishan, jay,
shreya, rohit, bansal], function(err) {
if (err) {
console.log(err);
} else {
console.log("successfully saved all the employees")
}
});

b) Create an HTML form using NodeJS and express for the employee to change the details when
he/she changes his/her vehicle by submitting his/her empid and the new vehicle details. The form
creation should use CSS for making it interactive and Use ExpressJS at the server-side.

CODE:
Html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>20BIT0005</title>
<style media="screen">
body {
text-align: center;
align-items: center;
justify-content: center;
}
form {
text-align: center;
align-items: center;
justify-content: center;
}
table {
margin: auto;
}
td {
padding: 10px 20px;
}
#submit-button {
padding: 5px;
background-color: lightblue;
margin: 20px;
}
</style>
</head>
<body>
<h1>Employee Vehicle detail form</h1>
<form action="/confirm" method="post">
<table>
<tr>
<td>Employee Id:</td>
<td><input type="number" name="empid" value="" /></td>
</tr>
<tr>
<td>Vehical No.:</td>
<td><input type="text" name="vehno" value="" /></td>
</tr>
<tr>
<td>Owner:</td>
<td><input type="text" name="owner" value="" /></td>
</tr>
<tr>
<td>Brand:</td>
<td><input type="text" name="brand" value="" /></td>
</tr>
<tr>
<td>Year:</td>
<td><input type="number" name="year" value="" /></td>
</tr>
</table>
<input type="submit" name="" value="submit" id="submit-button" />
</form>
</body>
</html>
Node js:
var express = require("express");
var bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/company', { useNewUrlParser:
true });
var app = express()
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
const compSchema = new mongoose.Schema({
empid: Number,
vehicalno: String,
owner: String,
brand: String,
year: Number
});
const Employee = mongoose.model("Employee", compSchema)
app.post('/confirm', function(req, res) {
var empid = req.body.empid;
var vehno = req.body.vehno;
var owner = req.body.owner;
var brand = req.body.brand;
var year = req.body.year;
Employee.findOneAndUpdate({ empid: empid }, { vehicalno: vehno, owner:
owner, brand: brand, year: year },
function(err) {
if (err) {
console.log(err);
} else {
res.send("Updation completed");
}
})
})
app.get("/", function(req, res) {
res.sendFile(__dirname + "/20BIT0005info.html")
})
app.listen(3000, function() {
console.log("server has started on 3000");
})

OUTPUT:

8. The IPL website has a MongoDB database of players. The following information about the players
are stored – name, IPL franchise, country, bid_amount a) Create an HTML form with appropriate CSS
containing text field. Name the text field as find and radio button(IPL, country, bid). Name the radio
button as find_details. On submitting an Express JS in Node server-side code is called that displays
information about b) The player if the name of the player is entered in find and no radio button is
checked. c) The players of a particular country representing IPL. If the radio button IPL is clicked and
country name is entered in find d) The player name, IPL franchise, and country for the player whose
bid amount is greater than or equal or bid amount given in find. if the bid radio button is checked
and the bid amount is entered in find. e) Store the data in MongoDB database

CODE:

Html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>20BIT0005</title>
<style media="screen">
body {
text-align: center;
align-items: center;
justify-content: center;
}
form {
text-align: center;
align-items: center;
justify-content: center;
}
table {
margin: auto;
}
td {
padding: 10px 20px;
}
#submit-button {
padding: 5px;
background-color: lightblue;
margin: 20px;
}
</style>
</head>
<body>
<h1>IPL detail form</h1>
<form action="/confirm" method="post">
<table>
<tr>
<td>Search:</td>
<td><input type="text" name="search" value="" /></td>
</tr>
<tr>
<td>Filter:</td>
<td>
<input type="radio" id="ipl" name="field" value="ipl"/>
<label for="ipl">IPL</label><br />
<input type="radio" id="country" name="field"
value="country" />
<label for="country">Country</label><br />
<input type="radio" id="bid" name="field" value="bid"/>
<label for="bid">Bid</label><br />
</td>
</tr>
</table>
<input type="submit" name="" value="submit" id="submit-button" />
</form>
</body>
</html>

Node js:
var bodyParser = require("body-parser");
const mongoose = require('mongoose');
var express = require("express");
mongoose.connect('mongodb://localhost:27017/ipl', { useNewUrlParser: true
});
var app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
const iplSchema = new mongoose.Schema({
name: String,
franchise: String,
country: String,
bid_amount: Number,
});
const Data = mongoose.model("Data", iplSchema)
const data1 = new Data({
name: "M.S.Dhoni",
franchise: "Rising Pune Super Gaints",
country: "India",
bid_amount: 500000
});
const data2 = new Data({
name: "Raina",
franchise: "Gujrat Lions",
country: "India",
bid_amount: 50000
});
const data3 = new Data({
name: "Bravo",
franchise: "Gujrat Lions",
country: "West Indies",
bid_amount: 200000
});
const data4 = new Data({
name: "Chris Gayle",
franchise: "Royal Challengers Banglore",
country: "West Indies",
bid_amount: 100000
});
const data5 = new Data({
name: "du Plessis",
franchise: "Rising Pune Super Gaints",
country: "South Africa",
bid_amount: 150000
});
const data6 = new Data({
name: "Virat Kohli",
franchise: "Royal Challengers Banglore",
country: "India",
bid_amount: 200000
});
const data7 = new Data({
name: "David Warner",
franchise: "Sunrisers Hyderabd",
country: "Australia",
bid_amount: 100000
});
const data8 = new Data({
name: "Sunil Narine",
franchise: "Kolkata Knight Riders",
country: "SriLanka",
bid_amount: 160000
});
Data.insertMany([data1, data2, data3, data4, data5, data6, data7, data8],
function(err) {
if (err) {
console.log(err);
} else {
console.log("successfully saved all the records")
}
});
app.post('/confirm', function(req, res) {
var search = req.body.search;
var filter = req.body.field;
if (filter === 'bid') {
Data.find({ bid_amount: { $gt: parseInt(search) } }, function(err,
data) {
if (err) {
console.log(err);
} else {
var html =
"<table><tr><th>Name</th><th>Franchise</th><th>Country</th><th>Bid</th></tr>";
data.forEach((data) => {
html +=
`<tr><td>${data.name}</td><td>${data.franchise}</td><td>${data.country}</td><t
d>${data.bid_amount}</td></tr>`
});
html += "</table>";
res.send(html);
}
})
} else if (filter === 'ipl' || filter === 'country') {
Data.find({ country: search }, function(err, data) {
if (err) {
console.log(err);
} else {
var html =
"<table><tr><th>Name</th><th>Franchise</th><th>Country</th><th>Bid</th></tr>";
data.forEach((data) => {
html +=
`<tr><td>${data.name}</td><td>${data.franchise}</td><td>${data.country}</td><t
d>${data.bid_amount}</td></tr>`
});
html += "</table>";
res.send(html);
}
})
} else {
Data.find({ name: search }, function(err, data) {
if (err) {
console.log(err);
} else {
var html =
"<table><tr><th>Name</th><th>Franchise</th><th>Country</th><th>Bid</th></tr>";
data.forEach((data) => {
html +=
`<tr><td>${data.name}</td><td>${data.franchise}</td><td>${data.country}</td><t
d>${data.bid_amount}</td></tr>`
});
html += "</table>";
res.send(html);
}
})
}
})
app.get("/", function(req, res) {
res.sendFile(__dirname + "/Q8.html")
})
app.listen(3000, function() {
console.log("server has started on 3000");
})

OUTPUT:

You might also like