0% found this document useful (0 votes)
17 views45 pages

T.J. Institute of Technology: Record Note Book

The document outlines the curriculum for the Full Stack Development Laboratory at T.J. Institute of Technology, detailing various exercises and projects to be completed by students. Each exercise focuses on different aspects of web development using technologies like JavaScript, Node.js, Express, and MongoDB. The document includes a bonafide certificate, an index of exercises, and specific programming tasks aimed at enhancing practical skills in full stack development.

Uploaded by

siva1prakash1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views45 pages

T.J. Institute of Technology: Record Note Book

The document outlines the curriculum for the Full Stack Development Laboratory at T.J. Institute of Technology, detailing various exercises and projects to be completed by students. Each exercise focuses on different aspects of web development using technologies like JavaScript, Node.js, Express, and MongoDB. The document includes a bonafide certificate, an index of exercises, and specific programming tasks aimed at enhancing practical skills in full stack development.

Uploaded by

siva1prakash1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

T.J.

INSTITUTE OF TECHNOLOGY
RAJIVGANDHISALAI,KARAPAKKAM,CHENNAI-600097

DEPARTMENT OF MASTER OF COMPUTER APPLICATION

RECORD NOTE BOOK

MC4212 – FULL STACK DEVELOPMENT LABORATORY

StudentName :

RegisterNumber :
T.J. INSTITUTE OF TECHNOLOGY
RAJIVGANDHI SALAI,KARAPAKKAM, CHENNAI-600097.

BONAFIDE CERTIFICATE

Certified that this is the bonafide record of work done by


Mr/Ms in Degree course
in the laboratory
during the academic year 2023

Station: Chennai–600097
Date :

Staff Incharge Head of the Department

Submitted for the University practical Examination held on at T.J. Institue of


Technology,karapakkam,chennai-600097.

INTERNAL EXAMINER EXTERNALEXAMINER


INDEX
S.NO DATE CONTENTS PAGE MARKS SIGNATURE
NO

1. CREATE A FORM AND VALIDATE THE


CONTENTS OF THE FORM USING JAVASCRIPT

2. GET DATA USING FETCH API FROM AN OPEN-


SOURCE ENDPOINT AND DISPLAY THE
CONTENTS THE FORM OF A CARD
3. CREATE A NODEJS SERVER THAT SERVES
STATIC HTML AND CSS FILES TO THE USER
WITHOUT USING EXPRESS

4. CREATE ANODEJS SERVER USING EXPRESS


THAT STORES DATA FROM A FORM AS A
JSON FILE AND DISPLAY IT IN ANOTHER
PAGE THE REDIRECT PAGE SHOULD BE
PREPARED USING HANDLEBARD
5. CREATE A NODEJS SERVER USING EXPRESS
THAT CREATES,READS,DATABASE,THE
INFORMATION ABOUT THE USER SHOULD BE
OBTAINED FROM A HTML FORM

6. CREATE A NODEJS SERVER THAT


CREATES,READ,UPDATES AND DELETE
EVENT DETAILS AND STORE THEM IN A
MYSQL DATA BASE.THE INFORMATION
ABOUT THE USER SHOULD BE OBTAINED
FROM A HTML FORM
7. CREATE A COUNTER USING REACT JS

8. CREATE A TODO APPLICATION USING


REACTJS.STORE THE DATA TO A JSON FILE
USING SIMPLE NODEJS SERVER AND RETRIVE
THE INFORMATION FROM THE SAME DURING
PAGE RELOADS
9. CREATE A SIMPLE SIGN UP AND LOGIN
MECHANISM AND AUTHENTICATE THE USER
USING COOKIES.THE USER INFORMATION
CAN BE STORES IN EITHER MONGODB OR
MYSQL AND THE SERVER SHOULD BE BUILD
USING NODEJS AND EXPRESS FRAMEWORK
10. CREATE AND DEPLOY A VIRTUAL MACHINE
USING A VIRTUAL BOX THAT CAN BE
ACCESSED FROM THE HOST COMPUTER
USING SSH
11. CREATE A DOCKER CONTAINER THAT WILL
DEPLOY A NODEJS PING SERVER USING THE
NODEJS IMAGE

1
Ex.No: 1 CREATE A FORM AND VALIDATE THE CONTENTS OF THE FORM USING JAVASCRIPT
Date:
Aim:
To create a form and validate the contents of the form using java script.

Procedure:-

➢ It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.
➢ JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server-side validation. Most of the web developers prefer JavaScript form validation.
➢ Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

Program:-
html :-

<!DOCTYPE html>
<head>
<title> FORM VALIDATION</title>
</head>
<style>
h1,p{
color:rgb(233, 22, 138);
}
</style>
<body>
<center>
<h1>THE CONTENTS OF THE FORM USING JAVASCRIPT</h1>
</center>
Enter the number : <input id="first"><br><br>
<button type="button" onclick="myFunction()">Submit</button>
<p id ="demo"></p>
<script src="sam.js"></script>
</body>
</html>
JS :-
function myFunction() {
let x = document.getElementById("first").value; let a;
if (isNaN(x) || x < 1 || x > 100) { a = "Input not valid";
} else {
a = "Input valid";
}
document.getElementById("demo").innerHTML = a;
}

2
Output:-

Result:-

Thus the create a form and validate the contents of the form using java script has been executedsuccessfully.

3
Ex.No: 2 GET DATA USING FETCH API FROM AN OPEN-SOURCE ENDPOINT AND DISPLAY THE
CONTENTS IN THE FORM OF A CARD
Date:
Aim:

To get data using Fetch API from an open-source endpoint and display the contents in the form a card.
Procedure:-

➢ First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a
variable (here api_url). Define a async function (here getapi()) and pass api_url in that function.
➢ Define a constant response and store the fetched data by await fetch() method. Define a constant
data and store the data in JSON form by await response.json() method. Now we got the data from
API by fetch() method in data variable.
➢ Pass this data variable to function which will show the data fetched.
➢ Function show takes the data variable and by applying for loop on data.list and getting all the rows
to show, it stores all the data to tab variable which set the innerHTML property for the class
employees in HTML file.

Program:-

Index3.html:

<!doctype html>
<html>
<head>
<script type=""text/javascript" src=""abc.json"></script>
<script type=""text/javascript">
function load(){
var mydata = JSON.parse(data);
alert(mydata.length);

var div = document.getElementById('data');

for(var i = 0;i < mydata.length; i++)


{
div.innerHTML + "<p class='inner' id="=i+">"+mydata[i].name +"</p>" + "<br>";

4
}
}
</script>
</head>
<body onload="load()">
<div id=""data">
</div>
</body>
</html>
abc.json:
data = '[{"name" : "udaya"},{"name" : "mani"},{"name" : "john"},{"name" : "Sunil"}]';

Name1.json:

5
Json1.js:

6
Output:-

Result:-
Thus the get data using Fetch API from an open-source endpoint and display the contents in the
form of a card have been executed successfully.

7
Ex.No: 3 CREATE A NODEJS SERVER THAT SERVES STATIC HTML AND CSS FILES TO
THE USER WITHOUT USING EXPRESS
Date:
Aim:
To create a NodeJS server that serves static HTML and CSS files to the user without using
Express.

Procedure:-

Step 1 — Setting up Express

To begin, run the following in your terminal:

Create a new directory for your project named express-static-file-tutorial:

➢ mkdir express-static-file-tutorial

Change into your new directory:

➢ cd express-static-file-tutorial

Initialize a new Node project with defaults. This will set a package.json file to access your dependencies:

➢ npm init -y

Create your entry file, index.js. This is where you will store your Express server:

➢ touch index.js

Install Express as a dependency:

➢ npm install express --save

Within your package.json, update your start script to include node and your index.js file.

Step 2 — Structuring Your Files

To store your files on the client-side, create a public directory and include an index.html file
along with an image.

Step 3 — Creating Your Express Server

In your index.js file, require in an Express instance and implement a GET request:

Step 4 — Serving Your Static Files

8
Express provides a built-in method to serve your static files:

app.use(express.static('public'));

Step 5 — Building Your Web Page

Navigate to your index.html file in the public directory.

Step 6 — Running Your Project

Program:-

var a,b,c,d; function addition1()


{
var a,b,c,n; a=Number(document.getElementById("first").value);
b=Number(document.getElementById("second").value); c= a + b;
document.getElementById("answer").innerHTML="ADD "+ c; return c;
}
const date = new Date();
// get the date as a string const n = date.toDateString();

// get the time as a string


const time = date.toLocaleTimeString(); document.getElementById("date").innerHTML="DATE :" +" "+ n;
console.log(n) document.getElementById("time").innerHTML="TIME :" +" "+ time; console.log(time)
var counter = 0; function increment(){
counter++; console.log(counter);
document.getElementById("inc1").innerHTML="INC" +" "+ counter;
}
function decrement(){ counter--; console.log(counter);
document.getElementById("inc1").innerHTML="INC" +" "+ counter;

}
document.getElementById("dna").innerHTML="CHECKING TAG.";
function abc(){
windows.alart("OK")
}
function names(){
var name="chandru"; document.getElementById("abcde").innerHTML=name;
}
var con;
con = () => "OK";
document.getElementById("abcde1").innerHTML = con(); var cin;
cin = () => "pondicherry"; document.getElementById("abcde2").innerHTML = cin();

index1.html
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>

9
<h1 id="date"></h1><br>
<h1 id="time"></h1><br>
<h1>HELLO</h1>
<div>
Enter the First number : <input id="first"> <br><br> Enter the Second number: <input
id="second"> <br>
<button onclick="addition1()">Add</button> <br>
<h1 id="answer"></h1>
</div>
<p id="dna" style="color: rgb(143, 223, 15);font-size: 50px;"></p>
<input type="button" onClick="increment()" value="Increment" />
<h1 id="inc1" ></h1>
<input type="button" onClick="decrement()" value="decrement" /><br><br>
<input type="button" onClick="names()" value="click" /><br><br>
<p id="abcde" style="color: blueviolet;font-size: 30px;"></p>
<p id="abcde1" style="color: blueviolet;font-size: 30px;"></p>
<p id="abcde2" style="color: blueviolet;font-size: 30px;"></p>
<script src="jsc.js"></script>
</body>
</html

Output:-

Result:-

Thus the NodeJS server that serves static HTML and CSS files to the user without using Expressbeen executed
successfully

10
Ex.No:4 CREATE A NODEJS SERVER USING EXPRESS THAT STORES DATA FROM A
FORM AS A JSON FILE AND DISPLAY IT IN ANOTHER PAGE. THE REDIRECT PAGE
SHOULD BE PREPARED USING HANDLEBARS
Date:
Aim:
To create a NodeJS server using Express that stores data from a form as a JSON file and displays
it in another page. The redirect page should be prepared using Handlebars.

Procedure:-

➢ JavaScript Object Notation, referred to as JSON in short, is one of the most popular formats for
data storage and data interchange over the internet. The simplicity of the JSON syntax makes it
very easy for humans and machines to read and write.
➢ Despite its name, the use of the JSON data format is not limited to JavaScript. Most programming
languages implement data structures that you can easily convert to JSON and vice versa.
➢ JavaScript, and therefore the Node.js runtime environment, is no exception. More often than not,
this JSON data needs to be read from or written to a file for persistence. The Node runtime
environment has the built-in fs module specifically for working with files.
➢ This article is a comprehensive guide on how to use the built-in fs module to read and write data
in JSON format. We shall also look at some third party npm packages that simplify working with
data in the JSON format.
➢ Serialization is the process of modifying an object or data structure to a format that is easy to store
or transfer over the internet. You can recover the serialized data by applying the reverse process.
➢ Deserialization refers to transforming the serialized data structure to its original format.

Program:-

Package install:

npm init –y
npm install express

Node4.js:
const express = require('express');
const app = express();
const path = require('path'); const router = express.Router();
router.get('/',function(req,res){ res.sendFile(path.join( dirname+'/index5.html'));
});
router.get('/about',function(req,res){ res.sendFile(path.join( dirname+'/about.html'));
});
router.get('/sitemap',function(req,res){ res.sendFile(path.join( dirname+'/sitemap.html'));
});
//add the router app.use('/', router);
app.listen(process.env.port || 3000);
console.log('Running at Port 3000');

11
About.html:
<!DOCTYPE html>
<head>
<title> FORM VALIDATION</title>
</head>
><style> h1{
color:rgb(233, 22, 138);
}
</style>
<body>
<center>
<h1>FULL STACK WEB DEVELOPMENT</h1>
<p>The Postman platform includes a comprehensive set of tools that help accelerate </p>
</center>
</body>
</html>

Index5.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Site</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384- ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<style>
body { padding-top: 50px; }
</style>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>EXPRESS IS WORKING WELL</h1>
</div>
</div>
</body>
</html>

Output:-

12
Result:-

Thus the NodeJS server using Express that stores data from a form as a JSON file and displays it
in another page. The redirect page should be prepared using Handlebars been executed successfully.

13
Ex.No: 5 CREATE A NODEJS SERVER USING EXPRESS THAT CREATES, READS,
UPDATES AND DELETE STUDENTS' DETAILS AND STORES THEM IN MONGODB
DATABASE. THE INFORMATION ABOUT THE USER SHOULD BE OBTAINED FROM A
HTML FORM.
Date:
Aim:
To create a NodeJS server using Express that creates, reads, updates and deletes students' details
and stores them in MongoDB database. The information about the user should be obtained from a HTML
form.

Procedure:-

➢ MongoDB stores data in BSON documents. BSON is a binary representation of JSON (JavaScript
Object Notation) documents. When you read MongoDB documentation, you'll frequently see the
term " Document " but you can think of a document as simply a JavaScript object. For those coming
from the SQL world, you can think of a document as being roughly equivalent to a row.

➢ MongoDB stores groups of documents in Collections - For those with a SQL background, you can
think of a collection as being roughly equivalent to a table.

➢ Every document is required to have a field named _id. The value of _id must be unique for each
document in a collection, is immutable, and can be of any type other than an array. MongoDB
will automatically create an index on _id. You can choose to make the value of _id meaningful
(rather than a somewhat random) if you have a unique value for each document that you'd like to
be able to quickly search.
Setup:-

➢ Download a copy of template.js


➢ Open template.js in your favorite code editor.
➢ Update the Connection URI to point to your Atlas cluster. If you're not sure how to do that, refer
back to the
➢ Save the file as crud.js.

Program:-

const express = require("express"); const mongoose = require("mongoose");

const foodRouter = require("./routes/foodRoutes.js"); const app = express();

app.use(express.json()); mongoose.connect(

// "mongodb+srv://udaytech18:Surya@[email protected]/sample?retryWrites=true&w=majority",

"mongodb+srv://krishnaraj:[email protected]/?retryWrites=true&w=majorit y",

useNewUrlParser: true, useFindAndModify: false, useUnifiedTopology: true

14
}

);

app.use(foodRouter); app.listen(3000, () => { console.log("Server is running...");

FOOD.JS:-

const mongoose = require("mongoose");

const FoodSchema = new mongoose.Schema({ name: {

type: String, required: true, trim: true, lowercase: true,

},

calories: { type: Number, default: 0,

validate(value) {

if (value < 0) throw new Error("Negative calories aren't real.");

},

},

});

const Food = mongoose.model("Food", FoodSchema); module.exports = Food;

FOODROUTERS.JS:

const mongoose = require("mongoose");


const FoodSchema = new mongoose.Schema({ name: {
type: String, required: true, trim: true, lowercase: true,
},
calories: {

type: Number, default: 0, validate(value) {


if (value < 0) throw new Error("Negative calories aren't real.");
},
},
});
const Food = mongoose.model("Food", FoodSchema); module.exports = Food;

PACKAGE.JSON:
{
"name": "crudmdb",
"version": "1.0.0",

15
"description": "",
"main": "server.js", "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC", "dependencies": { "express": "^4.17.1",
"mongoose": "^5.11.12"
}
}

Output:

16
Result:-

Thus the NodeJS server using Express that creates, reads, updates and deletes students' details andstores
them in MongoDB database. The information about the user should be obtained from a HTML form been
executed successfully.

17
Ex.No: 6 CREATE A NODEJS SERVER THAT CREATES, READS, UPDATES AND DELETE
EVENT DETAILS AND STORE THEM IN A MYSQL DATABASE. THE INFORMATION
ABOUT THE USER SHOULD BE OBTAINED FROM A HTML FORM.
Date:
Aim:
To create a NodeJS server that creates, reads, updates and deletes event details and stores them in
a MySQL database. The information about the user should be obtained from a HTML form.

Procedure:-

SampleNodeMySQL

➢ package.json
➢ script.js

➢ So let’s begin the application development by creating a directory for the project. Once you are
done, open the command prompt and navigate to your project directory. Now you need to set up
the project configurations for that, type in the below command and provide the necessary details:

1 npm init

Now, you need to install the required packages. In this project, I am using the below packages:

➢ express.js: It is a web framework.


➢ mysql: Node.js driver for MySQL
➢ body-parser: Helps in converting the POST data into the request body.
➢ nodemon: Helps in automatically restarting the server whenever the code changes.

In order to install these packages, type in the following command:

1npm i --s express express-handlebars mongoose body-parser


npm i -g nodemon

Once you are done installing with the packages, your final JSON file should look like the below file:

package.json

For that launch a new connection in MySQL Workbench. Once inside, create a new database with the
name ‘learners’. Now, within this database, create a new table with the name ‘learnerdetails’ and the
following columns:

➢ learner_id (INT) – Primary Key


➢ learner_name (VARCHAR)
➢ learner_email (VARCHAR)

18
➢ course_Id (INT)

➢ Coming back to the application, the next step is to create the script.js file which will help in
retrieving the data from the freshly created database. Script.js is the root file and also acts as the
entry point of this application. It will contain all the routers and drivers in it. Along with this, it is
also responsible for invoking the server and establish the connection.
➢ To create this file, you can use any code editor or IDE. I am using Webstorm IDE to develop this
application.

Program:-

Node6.js:

const express = require('express');

const bodyParser = require('body-parser'); const app = express();

const mysql = require('mysql');

/*npm init --y*/

/*npm install --save express mysql body-parser--*/ app.use(bodyParser.json());

const conn = mysql.createConnection({ host: 'localhost',

user: 'root', /* MySQL User */

/*password: 'root', MySQL Password */ database: 'stu_database' /* MySQL Database */

});

conn.connect((err) =>{

if(err) throw err;

19
console.log('Mysql Connected with App...');

});

/**

*Get All Items

*@return response()

*/

app.get('/api/items',(req, res) => {

let sqlQuery = "SELECT * FROM students";

let query = conn.query(sqlQuery, (err, results) => {

if(err) throw err;

res.send(apiResponse(results));

});

});

/**

*Get Single Item

*@return response()

*/

app.get('/api/items/:id',(req, res) => {

let sqlQuery = "SELECT * FROM students WHERE id=" + req.params.id;

let query = conn.query(sqlQuery, (err, results) => {

if(err) throw err;

res.send(apiResponse(results));

});

});

20
/**

*Create New Item

*@return response()

*/

app.post('/api/items',(req, res) => {

let data = {title: req.body.title, body: req.body.body};

let sqlQuery = "INSERT INTO students SET ?"; let query = conn.query(sqlQuery, data,(err, results) => {

if(err) throw err;

res.send(apiResponse(results));

});

});

/**

*Update Item

*@return response()

*/

app.put('/api/items/:id',(req, res) => {

let sqlQuery = "UPDATE students SET title='"+req.body.title+"', body='"+req.body.body+"' WHERE

id="+req.params.id;

let query = conn.query(sqlQuery, (err, results) => {

if(err) throw err;

res.send(apiResponse(results));

});

});

/**

21
*Delete Item

*@return response()

*/

app.delete('/api/items/:id',(req, res) => {

let sqlQuery = "DELETE FROM students WHERE id="+req.params.id+"";

let query = conn.query(sqlQuery, (err, results) => {

if(err) throw err;

res.send(apiResponse(results));

});

});

/**

*API Response

*@return response()

*/

function apiResponse(results){

return JSON.stringify({"status": 200, "error": null, "response": results});

app.listen(3000,() =>{

console.log('Server started on port 3000...');

})

22
Output:-

23
Result:-

Thus the NodeJS server that creates, reads, updates and deletes event details and stores them in a
MySQL database. The information about the user should be obtained from a HTML form been executed
successfully.

24
Ex.No: 7 CREATE A COUNTER USING REACTJS
Date:
Aim:
To create a counter using ReactJS.

Procedure:-

➢ Create a new React app using the following command: npx create-react-app my-app
➢ Next, open the app.js file and remove all the code present. We will write our counter code here. To startthe
local server or run the app, use the following command: npm start
➢ Get Started - Now we will create a simple functional component in the app.js page and also importthe
useState hook.
➢ Create HTML Elements - Now we will create the HTML code for the form. The styling will be done
later. We need to create two buttons and a span tag to show the output. There will be three buttons:
➢ +, - and reset.
➢ Validation Check - Now we will add an if statement to prevent the value of the counter from going into
negative digits. This is not necessary for this tutorial, as the counter is completely functional. But it is a
useful thing, as it is not practical for a counter to have a negative value. We will use an if statement to
make the minimum value 0. The if statement will be added in the decrease() function.
➢ CSS: The Icing on the Cake - Right now, the counter is completely functional, but it looks terrible. Now
we will do some CSS to style it. Create a new file called app.css (if it is not already create by default) and
add .
➢ Apply the Styles - Now import this CSS to the app.js file using the following code. import "./App.css"

Program:-

Package install:
Npx create-react-app react-basic
Cd react1
Npm start
App.js:
import React, { useState } from "react";
// Importing app.css is css file to add styling import "./App.css";
const App = () => {
const [counter, setCounter] = useState(0)
const handleClick1 = () => { setCounter(counter + 1)
}
const handleClick2 = () => { setCounter(counter - 1)
}
return (
<div> Counter App
<div>

25
{counter}
{counter>=20?"complete":null}
</div>
<div>
<button onClick={handleClick1}>Increment</button>
<button onClick={handleClick2}>Decrement</button>
</div>
</div>
)
}
export default App

Output:

26
-

RESULT:-

Thus the create a counter using ReactJS been executed successfully

27
Ex.No: 8 CREATE A TODO APPLICATION USING REACTJS. STORE THE DATA TO A
JSON FILE USING A SIMPLE NODEJS SERVER AND RETRIEVE THE INFORMATION
FROM THE SAME DURING PAGE RELOADS.
Date:
Aim:
To create a todo application using ReactJS. Store the data to a JSON file using a simple NodeJS
server and retrieve the information from the same during page reloads.

Procedure:-

➢ A JSON string can be stored in its own file, which is basically just a text file with an extension of
➢ .json, and a MIME type of application/json.
➢ If we loaded this string into a JavaScript program, parsed it into a variable called superHeroesfor
example, we could then access the data inside it using the same dot/bracket notation we looked at in
the JavaScript object basics article.
➢ For example:
➢ superHeroes.homeTown
superHeroes['active']
➢ To access data further down the hierarchy, you have to chain the required property names and array
indexes together. For example, to access the third superpower of the second hero listed in the members
list, you'd do this:
superHeroes['members'][1]['powers'][2]

❖ First we have the variable name — superHeroes.


❖ Inside that we want to access the members property, so we use ["members"].
❖ members contains an array populated by objects. We want to access the second object inside the
array, so we use [1].
❖ Inside this object, we want to access the powers property, so we use ["powers"].
❖ Inside the powers property is an array containing the selected hero's superpowers. We want the
third one, so we use [2].

Program:-

app.js
import React, { useState } from 'react';
import './App.css';

function App() {
const initialValue = [
"sleep", "office", "work", "mobile","playing"
]

28
const [ x, setMovies ] = useState(initialValue);

return (
<div className='App'>
{x.map((movie) => {
return <div key={movie}>{movie}</div>;
})}
</div>
);
}

export default App;

app.css:

.App {
text-align: center;
text-justify: auto;
text-indent: 5vh;
font-size: 5vh;

color:red;
background-color :blueviolet;
font-family:Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {


.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}

.App-header {
background-color: red;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

29
.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

Output:-

RESULT:-

Thus the Create a Todo application using ReactJS. Store the data to a JSON file using a simple
NodeJS server and retrieve the information from the same during page reloads been executed successfully.

30
Ex.No: 9 CREATE A SIMPLE SIGN UP AND LOGIN MECHANISM AND AUTHENTICATE
THE USER USING COOKIES. THE USER INFORMATION CAN BE STORED IN EITHER
MONGODB OR MYSQL AND THE SERVER SHOULD BE BUILT USING NODEJS AND
EXPRESS FRAMEWORK
Date:
Aim:
To create a simple Sign up and Login mechanism and authenticate the user using cookies. The
user information can be stored in either MongoDB or MySQL and the server should be built using
NodeJS and Express Framework.

Procedure:-

➢ $ npm install ejs - Embedded javaScript lets you generate HTML markup with plain JavaScript.
➢ $ npm install express –save - Express is a module framework for Node that you can use for applications.
➢ $ npm install mongoose - Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It
manages relationships between data, provides schema validation, and is used to translate between objects in
code and the representation of those objects in MongoDB.
➢ $ npm install body-parser –save - Body-parser allows express to read the body and then parse that into a
JSON object that we can understand.
➢ npm install express-session –save - Express.js uses a cookie to store a session id.
➢ npm install passport passport-local --save
➢ npm install passport-local-mongoose --save
➢ Passport is authentication middleware for Node. js. Extremely flexible and modular, Passport can be
unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support
authentication using a username and password, Facebook, Twitter, and more.
Program:-

Html:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width,minimum-scale=1">

<title>Login</title>

<!-- the form awesome library is used to add icons to our form -->

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">

31
<!-- include the stylesheet file -->

<link href="/style.css" rel="stylesheet" type="text/css">

</head>

<body>

<div class="login">

<h1>Login</h1>

<form action="/auth" method="post">

<label for="username">

<!-- font awesome icon -->

<i class="fas fa-user"></i>

</label>

<input type="text" name="username" placeholder="Username" id="username" required>

<label for="password">

<i class="fas fa-lock"></i>

</label>

<input type="password" name="password" placeholder="Password" id="password" required>

<input type="submit" value="Login">

</form>

</div>

</body>

</html>

Login.js:

const mysql = require('mysql'); const express = require('express');

const session = require('express-session'); const path = require('path');

const connection = mysql.createConnection({

host : 'localhost',

user : 'root',

password : '', database : 'nodelogin'

});

32
const app = express();

app.use(session({

secret: 'secret',

resave: true, saveUninitialized: true

}));

app.use(express.json());

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

app.use(express.static(path.join( dirname, 'static')));

// http://localhost:3000/

app.get('/', function(request, response) {

// Render login template


response.sendFile(path.join( dirname + '/login.html'));
});

// http://localhost:3000/auth
app.post('/auth', function(request, response) {
// Capture the input fields
let username = request.body.username;
let password = request.body.password;
// Ensure the input fields exists and are not empty
if (username && password) {
// Execute SQL query that'll select the account from the database based on the specified username
and password
connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?',
[username, password], function(error, results, fields) {
// If there is an issue with the query, output the error
if (error) throw error;
// If the account exists
if (results.length > 0) {
// Authenticate the user
request.session.loggedin = true;
request.session.username = username;
// Redirect to home page
response.redirect('/home');
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
});
} else {
response.send('Please enter Username and Password!');

33
response.end();
}
});

// http://localhost:3000/home
app.get('/home', function(request, response) {
// If the user is loggedin
if (request.session.loggedin) {
// Output username
response.send('Welcome back, ' + request.session.username + '!');
} else {
// Not logged in
response.send('Please login to view this page!');
}
response.end();
});

app.listen(3000);

db1.sql:

CREATE DATABASE IF NOT EXISTS `nodelogin` DEFAULT CHARACTER SET utf8 COLLATE
utf8_general_ci; USE
`nodelogin`;

CREATE TABLE IF NOT EXISTS `accounts` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES (1, 'test', 'test',
'[email protected]');

Output:-

34
35
RESULT:-

Thus the a simple Sign up and Login mechanism and authenticate the user using cookies. The user
information can be stored in either MongoDB or MySQL and the server should be built using NodeJS
and Express Framework been executed successfully.

36
Ex.No: 10 CREATE AND DEPLOY A VIRTUAL MACHINE USING A VIRTUAL BOX THAT
CAN BE ACCESSED FROM THE HOST COMPUTER USING SSH
Date:
Aim:
To create and deploy a virtual machine using a virtual box that can be accessed from the host
computer using SSH.

Procedure:-

➢ First we need to create or enable a Host-only network of VitualBox.Then we are going to telleach
one of our (currently one :) VirtualBoxes to use that network as well.
➢ Turn off your guest operating system.
➢ In order to create (or verify the existence of) a Host-Only networkclick on Global Tools in
thetop-right corner of the VirtualBox window.
➢ Here click on Host Network Manager, the lower of the two boxes.
➢ Here you might see 0 or more lines. The image is from an OSX host.I think on Windows hoststhe
"Name" field might hold some much longer name.
➢ If you don't have any entries then you need to create one.
➢ Click on the Create+ button in the top left corner.
➢ If your host operating system is MS Windows, this operation might need Windows Admin rights.Look
for the popup window that might bein the background.
➢ Set the IPV4 Address/Mask to 192.168.56.1/24 to be similar to mysetup. You don't need toenable
the DHCP server for our configuration, but it won't hurt either so if it is on, leave it on.
➢ Each VirtualBox guest needs to be configured to use the Host-only networkof VirtualBox.
➢ For this click on Machine Tools.
➢ Select your machine and click on Settings.
➢ Click on the Network tab.
➢ Install ssh server
➢ $ sudo apt-get install ssh
➢ $ ssh localhost
➢ IP-address server-key

Program:-
Node4.js:
const express = require('express');const
app = express();
const path = require('path'); const
router = express.Router();

37
router.get('/',function(req,res){
res.sendFile(path.join( dirname+'/index5.html'));
});
router.get('/about',function(req,res){
res.sendFile(path.join( dirname+'/about.html'));
});
router.get('/sitemap',function(req,res){
res.sendFile(path.join( dirname+'/sitemap.html'));
});

//add the router


app.use('/', router);
app.listen(process.env.port || 3000);
console.log('Running at Port 3000');

index5.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Site</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384- ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<style>
body { padding-top: 50px; }
</style>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>server hosting connectivity successfully</h1>
</div>
</div>
</body>
</html>

38
Server run host system:

“Host output”:

39
Host ip address:

40
Output: “client output”

RESULT:-

Thus create and deploy a virtual machine using a virtual box that can be accessed from the host
computer using SSH been executed successfully

41
Ex.No: 11 CREATE A DOCKER CONTAINER THAT WILL DEPLOY A NODEJS PING
SERVER USING THE NODEJS IMAGE
Date:
Aim:

To create a docker container that will deploy a nodejs ping server using the nodejs image.
Dockerfile
------------
# Use an official Node.js runtime as the base image
FROM node:14
# Set the working directory in the container WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package*.json ./
# Install dependencies RUN npm install #
Copy the server code to the working directory
COPY server.js .
# Expose the port that the server will listen on
EXPOSE 8080
# Define the command to run the server when the container starts
CMD ["node", "server.js"]

-------------
server.js
---------
const http = require('http');
// Create a simple HTTP server that responds with 'pong' for any request
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('pong\n');
});
// Start the server and listen on port 8080
server.listen(8080, () => {
console.log('Server running on port 8080');
})

42
Output:

RESULT:-
Thus create a docker container that will deploy a nodejs ping server using the nodejs image been
executed successfully.

43

You might also like