0% found this document useful (0 votes)
5 views81 pages

Sd-Ii-Ii Manual - N2

The document outlines a skill development course on Node.js, React.js, and Django offered by CMR Engineering College for the academic year 2023-2024. It provides an introduction to each technology, highlighting their key features, advantages, and examples of basic applications. Additionally, it compares Node.js, React.js, and Django, explaining their distinct roles in web development.

Uploaded by

sgogineni122
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)
5 views81 pages

Sd-Ii-Ii Manual - N2

The document outlines a skill development course on Node.js, React.js, and Django offered by CMR Engineering College for the academic year 2023-2024. It provides an introduction to each technology, highlighting their key features, advantages, and examples of basic applications. Additionally, it compares Node.js, React.js, and Django, explaining their distinct roles in web development.

Uploaded by

sgogineni122
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/ 81

CMR ENGINEERING COLLEGE

UGC AUTONOMOUS
(Accredited by NBA, Approved by AICTE NEW DELHI, Affiliated to JNTU, Hyderabad)
Kandlakoya, Medchal Road, Hyderabad-501 401

Department of Computer Science & Engineering

II YEAR II SEM: Skill Development Course


(NODE JS/REACT JS/DJANGO) (SD401PC)

REGULATION: R22

NAME :TDS PRANAV


ROLL NO : 228R1A05N2

A.Y: 2023-2024
Skill Development Course (NODE JS /REACT JS /DJANGO)

INTRODUCTION
NODE JS
Node.js is an open-source, cross-platform JavaScript runtime environment that allows
developers to run JavaScript code server-side. It uses the V8 JavaScript engine from Google
Chrome and enables developers to build scalable and efficient network applications. Node.js
is commonly used for building web servers, API servers, real-time applications, and various
other types of server-side applications.
Key features of Node.js include:
• Asynchronous and event-driven: Node.js uses non-blocking, asynchronous I/O
operations, which allows it to handle multiple connections simultaneously without
getting blocked. This architecture makes Node.js highly scalable and suitable for
building real-time applications.
• Single-threaded but highly scalable: Despite being single-threaded, Node.js can handle
thousands of concurrent connections efficiently due to its non-blocking I/O model.
• npm (Node Package Manager): npm is the default package manager for Node.js,
providing access to a vast ecosystem of libraries and tools that developers can use to
enhance their applications.
• JavaScript everywhere: Node.js enables developers to use JavaScript for both client-
side and server-side development, which promotes code reuse and simplifies the
development process for full-stack applications.
• Cross-platform: Node.js is compatible with various operating systems, including
Windows, macOS, and Linux, allowing developers to write code once and deploy it
across different environments.
• Overall, Node.js has gained widespread popularity in the web development community
due to its performance, scalability, and ease of use, making it a preferred choice for
building modern web applications.

ADVANTAGES OF NODE JS
Node.js offers several advantages for developers, making it a popular choice for building
server-side applications. Some of the key advantages of Node.js include:
Scalability: Node.js is well-suited for building highly scalable applications due to its non-
blocking, event-driven architecture. It can handle a large number of concurrent connections
efficiently, making it ideal for real-time applications such as chat applications, online gaming
platforms, and streaming services.
Performance: Node.js leverages the V8 JavaScript engine, which compiles JavaScript code
into machine code at runtime, resulting in fast execution speeds. Additionally, its non-blocking
I/O model allows applications to handle multiple requests simultaneously without blocking the
event loop, leading to improved performance.
JavaScript Everywhere: With Node.js, developers can use JavaScript for both client-side and
server-side development, enabling them to share code between the front end and back end of
their applications. This promotes code reuse, simplifies the development process, and reduces
the learning curve for developers who are already familiar with JavaScript.
Rich Ecosystem: Node.js has a vibrant ecosystem supported by npm (Node Package
Manager), which hosts over a million packages that developers can leverage to extend the
functionality of their applications. This vast library of modules covers a wide range of use
cases, from web frameworks and database drivers to utility libraries and tools for testing and
deployment.
Community Support: Node.js has a large and active community of developers who contribute
to its development, share knowledge, and provide support through forums, online communities,
and open-source projects. This community-driven approach ensures that developers have
access to resources, tutorials, and best practices to help them overcome challenges and build
high-quality applications.
Cross-Platform Compatibility: Node.js is cross-platform and can run on various operating
systems, including Windows, macOS, and Linux. This allows developers to write code once
and deploy it across different environments without making significant changes, streamlining
the development and deployment process.
Easy to Learn and Use: Node.js is relatively easy to learn, especially for developers who are
already familiar with JavaScript. Its event-driven, asynchronous programming model may
require some adjustment for developers coming from synchronous programming backgrounds,
but once mastered, it can lead to more efficient and scalable code.
Overall, Node.js offers a compelling set of advantages that make it a popular choice for
building modern, high-performance web applications.

EXAMPLE

Node.js script that creates a basic HTTP server

// Importing the HTTP module


const http = require('http');

// Creating a server instance


const server = http.createServer((req, res) => {
// Setting the response header
res.writeHead(200, {'Content-Type': 'text/plain'});

// Writing the response body


res.end('Hello, World!\n');
});

// Listening on port 3000


const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});

To run this script:


• Make sure you have Node.js installed on your machine. You can download it from
Node.js website.
• Copy the code into a file, for example, server.js.
• Open a terminal or command prompt and navigate to the directory where you saved
server.js.
• Run the command node server.js .
• You should see the message Server running at http://localhost:3000/ .
• Open a web browser and visit http://localhost:3000/ , you should see the text "Hello,
World!" displayed in the browser.
This example demonstrates how to create a basic HTTP server using Node.js. It listens on port
3000 and responds with "Hello, World!" to any incoming HTTP request.

REACT JS
React.js, commonly referred to as React, is an open-source JavaScript library for building user
interfaces (UIs) or UI components. It was developed by Facebook and has gained widespread
adoption in the web development community due to its declarative and component-based
approach to building user interfaces.
Some of the key advantages of React.js include:
Declarative Syntax: React allows developers to describe the UI state and how it should render
based on changes to that state. With its declarative syntax, developers can write cleaner and
more understandable code compared to imperative approaches.
Component-Based Architecture: React encourages a modular and reusable approach to
building UIs through its component-based architecture. Developers can create individual
components that encapsulate their own logic and UI, making it easier to manage and maintain
complex applications.
Virtual DOM (Document Object Model): React uses a virtual DOM to efficiently update the
UI. Instead of directly manipulating the browser's DOM, React creates a lightweight
representation of the DOM in memory and updates it based on changes to the UI state. This
minimizes the number of actual DOM manipulations, resulting in better performance.
One-Way Data Binding: React follows a unidirectional data flow, where data flows
downward from parent components to child components. This makes it easier to understand
how data is passed and manipulated within the application, reducing the likelihood of bugs and
making the codebase more maintainable.
JSX (JavaScript XML): React uses JSX, an extension of JavaScript that allows developers to
write HTML-like syntax directly within their JavaScript code. This approach makes it easier
to visualize and understand the structure of UI components, as well as to integrate HTML
seamlessly with JavaScript logic.
Rich Ecosystem and Community: React has a large and active community of developers who
contribute to its development, create reusable components, and provide support through
forums, documentation, and online resources. Additionally, React has a rich ecosystem of
libraries and tools, such as React Router for routing, Redux for state management, and React
Native for building native mobile applications.
Performance: React's efficient handling of the virtual DOM and its ability to selectively
update only the components that have changed contribute to improved performance compared
to traditional approaches. This makes React well-suited for building fast and responsive user
interfaces, even in large-scale applications.
Overall, React.js offers a powerful and flexible framework for building modern web
applications with dynamic and interactive user interfaces. Its combination of declarative
syntax, component-based architecture, and efficient rendering make it a popular choice for
developers seeking to create high-quality UIs.
EXAMPLE

React.js component that renders a basic "Hello, World!" message

// Importing the React library


import React from 'react';

// Defining a functional component named HelloWorld


const HelloWorld = () => {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
};

// Exporting the HelloWorld component to be used in other files


export default HelloWorld;

To run this React.js component:


• Make sure you have Node.js installed on your machine. You can download it from the
Node.js website.
• Set up a React.js project using Create React App or any other method you prefer. If you
haven't done this before, you can use Create React App by running npx create-react-
app my-app in your terminal, replacing my-app with the name of your project.
• Navigate to the directory of your React.js project in the terminal.
• Create a new file named HelloWorld.js inside the src directory of your project.
• Copy the code above into the HelloWorld.js file.
• You can now import and use the HelloWorld component in your App.js or any other
component:
import React from 'react';
import HelloWorld from './HelloWorld'; // Assuming HelloWorld.js is in the same directory

function App() {
return (
<div className="App">
<HelloWorld />
</div>
);
}

export default App;

• Run your React.js project by executing npm start in the terminal while inside your
project directory.
• Open a web browser and visit http://localhost:3000/, you should see the text "Hello,
World!" rendered on the page.
• This example demonstrates how to create a simple React.js component named
HelloWorld that renders "Hello, World!" inside an <h1> tag. You can then use this
component in your React.js application to display the message wherever needed.

DJANGO
Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. It follows the "batteries-included" philosophy, providing developers with a
set of tools and libraries to build web applications quickly and efficiently.
Some of the key advantages of Django include:
Rapid Development: Django's "batteries-included" approach means that it comes with many
built-in features and functionalities, such as an ORM (Object-Relational Mapping) system,
authentication, URL routing, form handling, and administrative interface. This allows
developers to focus on building application-specific features rather than reinventing the wheel.
DRY Principle (Don't Repeat Yourself): Django emphasizes the DRY principle by providing
reusable components and encouraging developers to write modular, reusable code. This helps
reduce code duplication, improves maintainability, and makes it easier to scale the application
as it grows.
ORM (Object-Relational Mapping): Django's built-in ORM simplifies database interactions
by allowing developers to work with database models using Python classes and methods, rather
than writing raw SQL queries. This abstraction layer makes it easier to perform common
database operations, such as querying, inserting, updating, and deleting records.
Admin Interface: Django comes with a powerful admin interface that can be automatically
generated based on the application's database models. This admin interface allows developers
and administrators to manage site content, user accounts, and other data without writing custom
admin panels.
Security: Django provides built-in protection against common security threats, such as SQL
injection, cross-site scripting (XSS), cross-site request forgery (CSRF), and clickjacking. It
also offers features like user authentication, session management, and secure password hashing
out of the box, helping developers build secure web applications by default.
Scalability: Django's architecture is designed to scale from small, single-server deployments
to large, high-traffic websites. It supports various deployment options, including traditional
web servers like Apache and Nginx, as well as cloud platforms like Heroku, AWS, and Google
Cloud Platform.
Community and Ecosystem: Django has a large and active community of developers who
contribute to its development, create reusable packages and libraries, and provide support
through forums, documentation, and online resources. This vibrant ecosystem makes it easier
for developers to find solutions to common problems, learn best practices, and stay up-to-date
with the latest developments in web development.
Overall, Django is a powerful and versatile framework for building web applications with
Python. Its emphasis on rapid development, clean design, and security makes it a popular
choice for developers of all skill levels.
EXAMPLE
Django application that defines a basic view to render "Hello, World!" on a webpage

1. First, make sure you have Django installed. You can install it using pip:
pip install Django
2. Create a new Django project using the following command:
django-admin startproject hello_world_project
3. Navigate into the project directory:
cd hello_world_project

4. Create a new Django app within the project:

python manage.py startapp hello_world_app


5. Open the views.py file inside the hello_world_app directory and define a view:
# hello_world_app/views.py
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello, World!")
6. Next, define a URL pattern for this view. Open the urls.py file inside the hello_world_app
directory:
# hello_world_app/urls.py

from django.urls import path


from . import views
urlpatterns = [
path('', views.hello_world, name='hello_world'),
]
7. Now, include the app's URLs in the project's URL configuration. Open the urls.py file inside
the hello_world_project directory:
# hello_world_project/urls.py

from django.contrib import admin


from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('hello_world_app.urls')),
]
8. You can now run the development server using the following command:
python manage.py runserver
9. Visit http://127.0.0.1:8000/ in your web browser, and you should see "Hello, World!"
displayed on the page.
This example demonstrates how to create a simple Django application with a single view that
renders "Hello, World!" when accessed.

DIFFERENCE BETWEEN NODE JS REACT JS AND JANGO


Node.js, React.js, and Django are all popular tools in web development, but they serve different
purposes and are used for different parts of the web application stack.
Node.js:
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers
to run JavaScript code on the server-side.
It is commonly used for building server-side applications, such as web servers, API servers,
and real-time applications.
Node.js uses an event-driven, non-blocking I/O model, which makes it efficient and scalable
for handling concurrent connections.
Node.js has a large ecosystem of packages and modules available through npm (Node Package
Manager), which developers can use to extend its functionality.
React.js:
React.js is a JavaScript library for building user interfaces. It is often used for building dynamic
and interactive UI components in web applications.
React.js follows a component-based architecture, where UIs are composed of reusable
components that manage their own state and can be composed together to build complex UIs.
React.js uses a virtual DOM (Document Object Model) to efficiently update the UI, minimizing
the number of actual DOM manipulations and improving performance.
React.js is typically used on the client-side, although it can also be rendered on the server-side
using tools like Next.js or Gatsby.js.
Django:
Django is a high-level Python web framework for building web applications. It follows the
"batteries-included" philosophy, providing developers with a set of tools and libraries for rapid
development.
Django is commonly used for building server-side web applications, including content
management systems (CMS), e-commerce platforms, and web APIs.
Django provides built-in features such as an ORM (Object-Relational Mapping) system,
authentication, URL routing, form handling, and an admin interface.
Django follows the MVC (Model-View-Controller) architectural pattern, where models
represent the data, views handle the presentation logic, and controllers (in Django called views)
handle the business logic and request handling.
In summary, Node.js is used for server-side JavaScript development, React.js is used for
building dynamic UI components on the client-side, and Django is used for server-side web
development with Python. While they can all be used together in a web application stack, they
serve different roles and have different strengths.
CONTENT

S.NO EXPERMENT NO PAGE NO REMARKS

1 Build a responsive web application for


shopping cart with registration, login, 1
catalog and cart pages using CSS3
features, flex and grid.
2 Make the above web application responsive
web application using Bootstrap 3
framework.
3 Use JavaScript for doing client side
validation of the pages implemented in 10
experiment 1 and experiment 2.
4 Explore the features of ES6 like arrow
functions, call backs, promises,
async/await. Implement an application for
reading the weather information 14
from openweathermap.org and display the
information in the form of a graph on
the web page.
5 Develop a java stand alone application
that connects with the database (Oracle / 21
mySql) and perform the CRUD
operation on the database tables
6 Create an XML for the bookstore
validates the same using both DTD AND 26
XSD
7 Design a controller with servlet that
provides the interaction with application 29
developed in experiment1 and the database
created in experiment5.
8 Maintaining the transaction history of any
user is important. Explore the 30
various session tracking mechanisms
(COOKIES, HTTP SESSION).
9 Create a custom server using http
module and explore the other modules 39
of Node JS like os,path,event.
10 Develop an express web application that
can interact with REST API to perform 41
CRUD operation on student data(postman).
11 For the above application create authorized
end points using 47
JWT.(JSONWEBTOKEN).
12 Create a React application for the student
management system having registration, 50
login, contact, about pages and implement
routing to navigate through these pages.
13 Create a service in the react that fetches the
weather information from open weather
map.org. and display the current and 56
historical weather information using
graphical representation using chart .js
14 Create a TODO application in react with
necessary components and deploy it into 61
github.

FACULTY HOD
Experiment 1

AIM: Build a responsive web application for shopping cart with registration, login,
catalog and cart pages using CSS3 features, flex and grid.

PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Shopping Cart</title>
</head>
<body>
<header>
<h1>CMR Shopping Cart</h1>
<nav>
<ul>
<li><a href="#catalog">Catalog</a></li>

<li><a href="#cart">Cart</a></li>
<li><a href="#login">Login</a></li>
<li><a href="#register">Register</a></li>
</ul>
</nav>
</header>

<main id="main-content">
<!-- Content will be dynamically loaded here using JavaScript -->
</main>

<footer>
<p> Thank you visit again</p>
</footer>
<script src="script.js"></script>
</body>
</html>

1
OUTPUT:

CMR Shopping Cart

• Catalog
• Cart
• Login
• Register

Thank you visit again.

2
Experiment 2

AIM: Make the above web application responsive web application using Bootstrap
framework.

PROGRAM:

Catalog.html
<!DOCTYPE html>
<html lang="en">
<!-- divinectorweb.com -->
<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>Responsive Product Card</title>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-
Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct"
crossorigin="anonymous"></script>
</head>
<body>

<div class="wrapper">
<div class="product-area">

<div class="img-area">
<img alt="Product 1" src="img/1.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>

<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
3
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.400
</div>
</div>
</div>

<div class="product-area">
<div class="img-area">
<img alt="" src="img/2.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.700
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/3.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
4
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
</div>
<div class="product-price">
Rs.2000
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/4.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.2500
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/5.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
5
</div>
<div class="product-price">
Rs.3000
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/6.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.300/-
</div>
</div>
</div>
</div>

</body>
</html>

OUTPUT:

Product 1
Add to Cart View Details
Product name

Rs.400

Add to Cart View Details


Product name

Rs.700
Add to Cart View Details
Product name
6
Rs.2000

Add to Cart View Details


Product name

Rs.2500

Add to Cart View Details


Product name

Rs.3000

Add to Cart View Details


Product name

Rs.300/-

Registration.html

<html>
<head>
<title> Registration Page </title>
</head>
<body bgcolor="Lightskyblue">
<br>
<br>
<form id="Reset">
<h1><bold> Student Registration Form </bold></h1>
<label> Firstname :</label>
<input type="text" name="firstname" size="30"/><br><br>
<label> Middlename: </label>
<input type="text" name="middlename" size="30"/><br><br>
<label> Lastname: </label>
<input type="text" name="lastname" size="30"/><br><br>

<label>
Course :
</label>
<select>
<option value=" Course ">Course</option>
<option value="B.Tech">B.Tech</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
7
<option value="M.Tech">M.Tech</option>
</select>

<br>
<br>
<label>
Gender :
</label><br>
<input type="radio" name="male" /> Male
<input type="radio" name="female"/> Female <br>

<br>
<br>

<label>
Phone :
</label>
<input type="text" name="country code" value="+91" size="2"/>
<input type="text" name="phone" size="10"/><br><br>
Address
<br>
<textarea cols="80" rows="5" value="address"></textarea><br>
<input type="button" name="submit" value="submit">
<input type = "button" value = "Reset" onClick = "fun()"/>
<script>
function fun(){
document.getElementById("Reset").reset();
}
</script>

OUTPUT:

Login.html
<!DOCTYPE html>
<html lang="en">
<head>

8
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Login Form Design using flexbox</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="form-box">
<div class="wrapper">
<div class="img-area">
<img src="1.png" alt="">
</div>
<div class="form-area">
<h3>Login Form</h3>
<form>
<div class="single-form">
<input type="text" placeholder="Username" />
</div>
<div class="single-form">
<input type="password" placeholder="Password" />
</div>
<input type="submit" value="Login"/>
</form>
</div>
</div>
</div>
</body>
</html>

OUTPUT:

9
Experiment 3

AIM: Use JavaScript for doing client side validation of the pages implemented in experiment 1
and experiment 2.

PROGRAM:

Login Validation.html
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style all input fields */
input {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
}

/* Style the submit button */


input[type=submit] {

background-color: #04AA6D;
color: white;
}

/* Style the container for inputs */


.container {
background-color: #f1f1f1;
padding: 20px;
}

/* The message box is shown when the user clicks on the password field */
#message {
display:none;
background: #f1f1f1;
color: #000;
position: relative;
padding: 20px;
margin-top: 10px;
}

#message p {
padding: 10px 35px;
10
font-size: 18px;
}

/* Add a green text color and a checkmark when the requirements are right */
.valid {
color: green;
}

.valid:before {
position: relative;
left: -35px;
content: "✔";
}

/* Add a red text color and an "x" when the requirements are wrong */
.invalid {
color: red;
}

.invalid:before {
position: relative;
left: -35px;
content: "✖";
}
</style>
</head>
<body>

<h3>Password Validation</h3>
<p>Try to submit the form.</p>

<div class="container">
<form action="/action_page.php">
<label for="usrname">Username</label>
<input type="text" id="usrname" name="usrname" required>

<label for="psw">Password</label>
<input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must
contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>

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


</form>
</div>

<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
11
</div>
<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");

// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}

// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}

// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}

// Validate capital letters


var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}

// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}

12
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>
</body>
</html>

OUTPUT:

13
Experiment 4
AIM: Explore the features of ES6 like arrow functions, call backs, promises,
async/await. Implement an application for reading the weather information
from openweathermap.org and display the information in the form of a graph on
the web page.

Features of ES6

ES6, or ECMAScript 2015, introduced several powerful features to JavaScript, including arrow
functions, callbacks, promises, and async/await. Let&#39;s explore each of these features:
1. Arrow Functions:
• Arrow functions provide a more concise syntax for writing anonymous functions.
• They use the =&gt; syntax.
• They don&#39;t bind their own this, arguments, super, or new.target.
• They are especially useful for short, one-liner functions and for maintaining the context
of this in callbacks.

EXAMPLE

// ES5
var double = function(x) {
return x * 2;
};

// ES6
const double = x =&gt; x * 2;

2. Callbacks:
• Callbacks are functions passed as arguments to other functions, to be executed later.
• They are commonly used in asynchronous programming to handle events or
• asynchronous operations.
• Callback functions can be synchronous or asynchronous.

EXAMPLE:

function fetchData(callback) {
// Simulating an asynchronous operation
setTimeout(() =&gt; {
const data = &#39;Some data fetched&#39;;
callback(data);
}, 1000);
}

fetchData(data =&gt; {
console.log(data);
14
});
3. Promises:

• Promises are objects representing the eventual completion or failure of an asynchronous


• operation.
• They provide a cleaner alternative to callbacks for handling asynchronous operations.
• Promises have methods like then() and catch() to handle success and failure respectively.

EXAMPLE:

function fetchData() {
return new Promise((resolve, reject) =&gt; {
// Simulating an asynchronous operation
setTimeout(() =&gt; {
const data = &#39;Some data fetched&#39;;
resolve(data);
}, 1000);
});
}

fetchData()
.then(data =&gt; {
console.log(data);
})
.catch(error =&gt; {
console.error(error);
});

4. Async/Await:

• Async/await is a syntax for writing asynchronous code that looks synchronous, making it
• easier to read and understand.
• It is built on top of promises.
• async keyword is used to define an asynchronous function, and await is used to pause
• execution until a promise is settled.

EXAMPLE:

async function fetchData() {


// Simulating an asynchronous operation
return new Promise(resolve =&gt; {
setTimeout(() =&gt; {
const data = &#39;Some data fetched&#39;;
resolve(data);
}, 1000);
});
}

15
async function processData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {

console.error(error);
}
}

processData();

PROGRAM:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Graph</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}

.container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
text-align: center;
}

.graph-container {
margin-bottom: 20px;
}

.input-container {
display: flex;
justify-content: center;
}

16
#cityInput {
padding: 10px;
border-radius: 5px 0 0 5px;
border: 1px solid #ccc;
outline: none;
}

#fetchWeatherBtn {
padding: 10px 20px;
background-color: #007bff;
border: none;
color: #fff;
border-radius: 0 5px 5px 0;
cursor: pointer;
outline: none;
}

#fetchWeatherBtn:hover {
background-color: #0056b3;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container">
<h1>Weather Graph</h1>
<div class="graph-container">
<canvas id="weatherChart"></canvas>
</div>
<div class="input-container">
<input type="text" id="cityInput" placeholder="Enter city name">
<button id="fetchWeatherBtn">Fetch Weather</button>
</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
const apiKey = '7e43491c95b913ec443a233dc358de79';

const weatherChartCanvas = document.getElementById('weatherChart');


const ctx = weatherChartCanvas.getContext('2d');

let weatherChart;

document.getElementById('fetchWeatherBtn').addEventListener('click', function() {
const cityInput = document.getElementById('cityInput');
const city = cityInput.value.trim();

if (city === '') {


alert('Please enter a city name.');
17
return;
}

fetchWeatherData(city)
.then(data => {
const weatherData = extractWeatherData(data);
renderChart(weatherData);
})
.catch(error => {
console.error('Error fetching weather data:', error);
alert('Failed to fetch weather data. Please try again.');
});
});

async function fetchWeatherData(city) {


const apiUrl =
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
const response = await fetch(apiUrl);
return response.json();
}

function extractWeatherData(data) {
return {
temperature: data.main.temp,
humidity: data.main.humidity,
pressure: data.main.pressure
};
}

function renderChart(weatherData) {
if (weatherChart) {
weatherChart.destroy();
}

weatherChart = new Chart(ctx, {


type: 'bar',
data: {
labels: ['Temperature', 'Humidity', 'Pressure'],
datasets: [{
label: 'Weather Information',
data: [weatherData.temperature, weatherData.humidity, weatherData.pressure],
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
18
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
});
</script>
</body>
</html>

OUTPUT

19
20
Experiment 05

AIM: Develop a java stand alone application that connects with the database (Oracle / mySql) and
perform the CRUD operation on the database tables

PROGRAM:
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HTTPServlet{

public void service(HttpServletRequest request,HttpServletResponse response)

try {

PrintWriter out=response.getWriter();

out.print("<h1>Hello Eclipse</h1>");

}catch(Exception e)

e.printStackTrace();

import java.sql.*;
import java.util.Scanner;
public class InsertData {
public static void main(String[] args) {
try {
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();
21
// To read insert data into student table
Scanner sc = new Scanner(System.in);
System.out.println("Inserting Data into student table : ");
System.out.println(" ");
System.out.print("Enter student id : ");
int sid = sc.nextInt();
System.out.print("Enter student name : ");
String sname = sc.next();
System.out.print("Enter student address : ");
String saddr = sc.next();
// to execute insert query
s.execute("insert into student values("+sid+",'"+sname+"','"+saddr+"')");
System.out.println("Data inserted successfully into student table");

s.close();
con.close();
} catch (SQLException err) {
System.out.println("ERROR: " + err);
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}

UpdateData.java

import java.sql.*;
import java.util.Scanner;
public class UpdateData {
public static void main(String[] args) {
try {
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();

// To read insert data into student table


Scanner sc = new Scanner(System.in);
System.out.println("Update Data in student table : ");
System.out.println(" ");
System.out.print("Enter student id : ");
int sid = sc.nextInt();
System.out.print("Enter student name : ");
String sname = sc.next();
System.out.print("Enter student address : ");
String saddr = sc.next();
// to execute update query

22
s.execute("update student set s_name='"+sname+"',s_address = '"+saddr+"' where s_id = "+sid);
System.out.println("Data updated successfully");
s.close();
con.close();
} catch (SQLException err) {
System.out.println("ERROR: " + err);
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}

DeleteData.java

import java.sql.*;
import java.util.Scanner;
public class DeleteData {
public static void main(String[] args) {
try {
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();

// To read insert data into student table


Scanner sc = new Scanner(System.in);
System.out.println("Delete Data from student table : ");
System.out.println(" ");
System.out.print("Enter student id : ");
int sid = sc.nextInt();
// to execute delete query
s.execute("delete from student where s_id = "+sid);
System.out.println("Data deleted successfully");
s.close();
con.close();
} catch (SQLException err) {
System.out.println("ERROR: " + err);
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}

DisplayData.java

import java.sql.*;
import java.util.Scanner;
public class DisplayData {
public static void main(String[] args) {
try {
23
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();

// To display the data from the student table


ResultSet rs = s.executeQuery("select * from student");
if (rs != null) {
System.out.println("SID \t STU_NAME \t ADDRESS");
System.out.println(" ");
while (rs.next())
{
System.out.println(rs.getString(1) +" \t "+ rs.getString(2)+ " \t "+rs.getString(3));
System.out.println(" ");
}
s.close();
con.close();
}
} catch (SQLException err) {
System.out.println("ERROR: " + err);
} catch (Exception err) {
System.out.println("ERROR: " + err);
}

}
}

OUTPUT

24
25
Experiment 06
AIM: create an XML for the bookstore validates the same using both DTD AND XSD.

An XML document that is well created can be validated using DTD (Document Type Definition) or XSD
(XML Schema Definition). A well-formed XML document should have correct syntax and should follow the
below rules:
• It must start with the XML declaration.

• It must have one unique root element enclosing all the other tags.

• All start tags must have end tags.

• XML tags are case-sensitive.

• All elements must be closed with the proper ending tag.

• All elements must be nested properly.

• All attributes’ values must be in quotes.

• For special characters, XML entities must be used.

• It must start with the XML declaration.

• It must have one unique root element enclosing all the other tags.

• All start tags must have end tags.

• XML tags are case-sensitive.

• All elements must be closed with the proper ending tag.

• All elements must be nested properly.

• All attributes’ values must be in quotes.

• For special characters, XML entities must be used.

26
Difference between DTD and XSD

DTD XSD
DTD refers to Document Type Definition. XSD refers to XML Schema Definition.
These are derived from SGML syntax. These are written in XML.
It does not support datatypes. It supports datatypes.
It does not support namespaces. It supports namespaces.
It does not define the order of child elements. It defines the order of child elements.
It is not extensible. It is extensible.
It is not simple and easy to learn. It is simple and easy to learn.
It provides less control over the XML structure. It provides more control over the XML
structure.
PROGRAM:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>BookStore</title>
</head>
<body>
<table border="2">
<tr>
<th>Bookname</th>
<th>Author</th>
<th>Publisher</th>
<th>Edition</th>
<th>Price</th>
</tr>
<tr>
<td>Web Technology</td>
<td>Robet Roy</td>
<td>Technical</td>
<td>7th</td>
<td>650</td>
</tr>
<tr>
<td>Software Engineering</td>
<td>Ugrasen Suman</td>
<td>Technical</td>
<td>8th</td>

27
<td>450</td>
</tr>
<tr>
<td>DWDM</td>
<td>Vipin Kumar</td>
<td>Technical</td>
<td>5th</td>
<td>399</td>
</tr>
<tr>
<td>Computer Networks</td>
<td>Forouzan</td>
<td>Technical</td>
<td>7th</td>
<td>500</td>
</tr>
<tr>
<td>D.A.A</td>
<td>T.H.Cormen</td>
<td>Technical</td>
<td>7th</td>
<td>600</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

OUTPUT

28
Experiment-7

AIM: Design a controller with servlet that provides the interaction with application developed in
experiment1 and the database created in experiment5.

PROGRAM:
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet { @Override


public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Set the response message's MIME type response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket PrintWriter out = response.getWriter();

// Write the response message, in an HTML page try {


out.println("<!DOCTYPE html>"); out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); out.println("<title>Hello,
World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>"); out.println("<p>Protocol: " + request.getProtocol() +
"</p>"); out.println("<p>PathInfo: " + request.getPathInfo() + "</p>"); out.println("<p>Remote Address: " +
request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>"); out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}
}

OUTPUT:

29
Experiment-8

AIM: Maintaining the transaction history of any user is important. Explore the
various session tracking mechanisms (COOKIES, HTTP SESSION).

COOKIES IN SERVLET
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie with response
from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user,
cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user
logout or signout.

30
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

How to create Cookie


Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response

PROGRAM:

Login form for cookies


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>cookies servlet</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="form-box">
<div class="wrapper">
<div class="img-area">
<imgsrc="1.png" alt="">
</div>
<div class="form-area">
<h3>Login Form</h3>
<form>
<div class="single-form">
<input type="text" placeholder="Username" />
31
</div>
<div class="single-form">
<input type="password" placeholder="Password" />
</div>
<input type="submit" value="Login"/>
</form>
</div>
</div>
</div>
</body>
</html

Adding cookies servlet


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet{
public void doPost(HttpServletRequestreq,HttpServletResponse res)throws IOExeption,ServletException{
String name = req.getParameter ("name");
String pwd = req.getParameter ("pwd");
Cookie c1 = new Cookie ("name", name);
Cookie c2 = new Cookie("pwd", pwd);
res.addCookie(c1);
res.addCookie(c2);
res.setContentType("text/html");
PrintWriter pw = res .getWriter();
pw. println ("Welcome to my Website"+name);
pw.println(“<h3><a href=’getcookiesServlet’>Request Again</a></h3>”);
pw.close();
}

Get cookies servlet


import java.io.*;

32
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet{
public void doGet(HttpServletRequestreq, HttpServletResponse res)throws IOException, ServletException{
Cookie c[] = req.getCookies);
printWritern pw = res.getwriter();
res.setContentType(“text/html”);
for (inti=0;i<c.length;i++){
String name = c[i].getName();
String value = c[i].getValue();
pw.printin("name="+name+" "+"value="+value);
pw.close();
}
}

Web file
‹?xml version="1.0" encoding="UTF-8" ?>
<web-app>
< servlet>
< servlet-name>AddCookieServlet</servlet-name>
< servlet-class>AddCookieServlet</servlet-class>
</servlet>
<servlet>
< servlet-name>GetCookiesServlet</servlet-name>
< servlet-class>GetCookiesServlet</servlet-class>
</servlet>
< servlet-mapping>
< servlet-name>AddCookieServlet</servlet-name>
<url-pattern>/AddCookieServlet</url-pattern>
</servlet-mapping>
<servlet-mapping >
< servlet-name>GetCookiesServlet</servlet-name>
‹url-pattern>GetCookiesservlet/se-pattern>

33
</servlet-mapping>
‹welcome-file-list>
‹welcome-file > AddCookie.html</welcome-file>
‹welcome-file> AddCookie.htm</welcome-file>
</welcome-file-list>
</web-app>

OUTPUT

34
VSCODE PROGRAM:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Tracking Mechanism</title>
</head>
<body>
<h1>Welcome to our website!</h1>
<p>This is a basic example of cookie-based session tracking.</p>
<script>
// Function to set a cookie
functionsetCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();

35
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

// Function to get a cookie value by name


functiongetCookie(name) {
varnameEQ = name + "=";
var ca = document.cookie.split(';');
for (vari = 0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) == 0) {
returnc.substring(nameEQ.length, c.length);
}
}
return null;
}

// Function to check if a session ID exists in the cookie


functioncheckSession() {
varsessionId = getCookie('sessionId');
if (sessionId) {
// If session ID exists, welcome back the user
alert("Welcome back! Your session ID is: " + sessionId);
} else {
// If no session ID exists, create a new one and set the cookie
sessionId = generateSessionId();
setCookie('sessionId', sessionId, 1); // Set the session ID cookie to expire in 1 day
alert("Welcome! Your session ID is: " + sessionId);
}
}

36
// Function to generate a random session ID
functiongenerateSessionId() {
returnMath.random().toString(36).substr(2, 9); // Generate a random string
}

// Call the checkSession function when the page loads


window.onload = checkSession;
</script>
</body>
</html>
OUTPUT

37
38
Experiment-9

AIM: Create a custom server using http module and explore the other modules of
Node JS like os,path,event.

PROGRAM:

// Step 1: Import required modules


const http = require('http');
constos = require('os');
const path = require('path');
const { EventEmitter } = require('events');

// Step 2: Create an instance of EventEmitter


consteventEmitter = new EventEmitter();

// Step 3: Create a simple HTTP server


const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type':'text/plain' });
res.end('Hello, World!\n');
});

// Step 4: Define server port and hostname


const port = process.env.PORT || 3000;
constport = 3000;
consthostname = '127.0.0.1';
const os = require('os');

// Step 5: Listen for requests on the specified port and hostname


const hostname = '127.0.0.1';
server.listen(port, hostname, () => {
console.log('Server running at http://${hostname}:${port}/');
});

39
// Step 6: Print OS information
console.log('OS Type:', os.type());
console.log('OS Platform:', os.platform());
console.log('OS Architecture:', os.arch());
console.log('CPU Cores:', os.cpus().length);

// Step 7: Print current working directory


console.log('Current Working Directory:', process.cwd());

// Step 8: Join paths using the path module


constjoinedPath = path.join( dirname, 'public', 'images');
console.log('Joined Path:', joinedPath);

// Step 9: Handle a custom event


eventEmitter.on('customEvent', (data) => {
console.log('Custom Event Triggered:', data);
});

// Step 10: Emit a custom event


eventEmitter.emit('customEvent', { message:'Hello from custom event!' });

OUTPUT

40
Experiment-10

AIM Develop an express web application that can interact with REST API to
perform CRUD operation on student data(postman).

PROGRAM:
Firstly we need to create a new folder and open the folder in the command prompt and enter a
command as below

npm init -y

• Open that folder in the vscode by entering code.


• Next in the terminal we need to install all the packages we need, so we mainly use express
and sqlite3.
• The Command to install express and sqlite3 is

• npm install express sqlite3

Then create file named as the app.js and db.js

const sqlite3 = require('sqlite3').verbose();

// Function to initialize the database schema


function initializeDatabase() {
const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the SQLite database.');
createStudentsTable(db);
}
});

// Close the database connection when the Node process exits


process.on('exit', () => {
db.close((err) => {
if (err) {
console.error(err.message);
} else {
console.log('Disconnected from the SQLite database.');

41
}
});
});
}
// Function to create the 'students' table if it doesn't exist
function createStudentsTable(db) {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
grade TEXT
);
`;

db.run(createTableQuery, (err) => {


if (err) {
console.error(err.message);
} else {
console.log('The students table has been created or already exists.');
}
});
}

module.exports = { initializeDatabase }
const express = require('express');
const sqlite3 = require('sqlite3');
const{ initializeDatabase } = require('./db');
const app = express();
const port = 3000;

// Connect to SQLite database


const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.log(err.message);
} else {
console.log('Connected to the SQLite database.');
}
});

// Middleware to parse request body as JSON


app.use(express.json());

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


res.send('Welcome to the Student');
});

42
// Get all Students
app.get('/students', (req, res) => {
db.all('SELECT * FROM students', [], (err, rows) => {
if (err) {
return console.error(err.message);
}
res.json(rows);
});
});

// Get a single student by id


app.get('/students/:id', (req, res) => {
const id = req.params.id;
db.all('SELECT * FROM students WHERE id = ?', [id], (err, row) => {
if (err) {
return console.error(err.message);
}
res.json(row);
});
});

// Create a new student


app.post('/students', (req, res) => {
const{ name, age, grade } = req.body;
db.run('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)', [name, age, grade],
function (err) {
if (err) {
return console.error(err.message);
}
res.status(201).json({ id:this.lastID });
});
});

// Update a student
app.put('/students/:id', (req, res) => {
const id = req.params.id;
const{ name, age, grade } = req.body;
db.run('UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?', [name, age,
grade, id], function (err) {
if (err) {
return console.error(err.message);
}
res.json({ updatedID:id });
});
});

43
// Delete a student
app.delete('/students/:id', (req, res) => {
const id = req.params.id;
db.run('DELETE FROM students WHERE id = ?', id, function (err) {
if (err) {
return console.error(err.message);
}
res.json({ deletedID:id });
});
});

app.listen(port, () => {
console.log('Server running at http://localhost:${port}');
});

OUTPUT
GET:
• Open Postman.
• Set the request type to GET.
• Enter the URL: http://localhost:3000/students.

POST : Create a New Student


• Open Postman.
• Set the request type to POST.
• Enter the URL: http://localhost:3000/students.
• Go to the "Body" tab.
• Select raw and set the body to JSON format.

44

GET: #all Students


• Set the request type to GET.
• Enter the URL: http://localhost:3000/students.
• Click on the "Send" button
• You should receive a response with details of all students in your SQLite database.

45
DELETE:
• Set the request type to DELETE.
• Enter the URL for the student you want to delete (replace: id with an actual student
ID): http://localhost:3000/students/:id
• Place instead of ID which replace with number that is ID to be deleted.
• Then click send

PUT:
• Set the request type to PUT.
• Enter the URL for the student you want to delete (replace: id with an actual student
ID): http://localhost:3000/students/:id
• Go to the "Body" tab.
• Select raw and set the body to JSON format

46
Experiment 11
AIM : For the above application create authorized end points using
JWT.(JSONWEBTOKEN).
PROGRAM:
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const secretKey = "secretKey";

app.get("/", (req, resp) => {


resp.json({
message: "a simple api"
})
})
app.post("/login", (req, resp) => {
const user = {
id: 1,
username: "Manasa",
email: "abc@test.com"
}
jwt.sign({ user }, secretKey, { expriesIn: '300s' }, (err, token) => {
resp.json({
token
})
})
})
app.post("/profile",verifyToken,(req,resp,next)=>{
jwt.verify(req.token,secretKey,(err,authData)=>{
if (err) {
resp.send({ result:"invalid Token"});
}else{
resp.json({
message:"profile Accessed",
authData

})
} })
})
function verifyToken(req,resp,next){
const brearerHeader = req.headers['authorization'];
if(typeof bearerHeader !=='undefined'){
const bearer = bearerHeader.split(" ");
const token= token;
next();

47
}else {
resp.send({
result:'Token is not valid'
})
}
}

app.listen(5000, () => {
console.log("app is running on 5000 port");
})

OUTPUT

48
49
Experiment-12

AIM: Create a React application for the student management system having
registration, login, contact, about pages and implement routing to navigate through
these pages.

PROGRAM:
Steps to create the React application:

Step 1: Create React Project

npm init react-app myapp

Step 2: Change your directory and enter your main folder.

Cd myreactapp

Project Structure:

50
// Filename - App.js

import './App.css';
import Form from "./Form"

function App() {
return (
<div className="App">
<Form />
</div>

);
}

export default App;

// Filename - Form.js

import { useState } from "react";

export default function Form() {


// States for registration
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

// States for checking the errors


const [submitted, setSubmitted] = useState(false);
const [error, setError] = useState(false);

// Handling the name change


const handleName = (e) => {
setName(e.target.value);
setSubmitted(false);
};

// Handling the email change


const handleEmail = (e) => {
setEmail(e.target.value);
setSubmitted(false);
};

// Handling the password change


const handlePassword = (e) => {
setPassword(e.target.value);
setSubmitted(false);

51
};

// Handling the form submission


const handleSubmit = (e) => {
e.preventDefault();
if (name === "" || email === "" || password === "") {
setError(true);
} else {
setSubmitted(true);
setError(false);
}
};

// Showing success message


const successMessage = () => {
return (
<div
className="success"
style={{
display: submitted ? "" : "none",
}}
>
<h1>User {name} successfully registered!!</h1>
</div>
);
};

// Showing error message if error is true


const errorMessage = () => {
return (
<div
className="error"
style={{
display: error ? "" : "none",
}}
>
<h1>Please enter all the fields</h1>
</div>
);
};

return (
<div className="form">
<div>
<h1>User Registration</h1>
</div>

52
{/* Calling to the methods */}
<div className="messages">
{errorMessage()}
{successMessage()}
</div>

<form>
{/* Labels and inputs for form data */}

<label className="label">Name</label>
<input
onChange={handleName}
className="input"
value={name}
type="text"
/>

<label className="label">Email</label>
<input
onChange={handleEmail}
className="input"
value={email}
type="email"
/>

<label className="label">Password</label>
<input
onChange={handlePassword}
className="input"
value={password}
type="password"
/>

<button onClick={handleSubmit} className="btn"


type="submit">
Submit
</button>
</form>
</div>
);
}

/* Filename: App.css */

.App {

53
text-align: center;
background-color: green;
}

.label {
display: block;
font-size: larger;
color: white;
padding: 5px;
}

.input {
font-size: larger;
padding: 5px;
margin: 2px;

.btn {
color: white;
background-color: red;
border-radius: 5px;
font-size: larger;
display: block;
padding: 5px;
margin: 10px auto;
}

.messages {
display: flex;
justify-content: center;
}

.error {
display: block;
background-color: red;
color: white;
width: fit-content;
height: 50px;
padding: 5px;
}

.success {
display: block;
background-color: lightblue;
color: black;

54
width: fit-content;
height: 50px;
padding: 5px;
}

OUTPUT

55
Experiment 13

AIM: Create a service in the react that fetches the weather information from open
weather map.org. and display the current and historical weather information using
graphical representation using chart .js .

PROGRAM:
Step 1: Create an OpenWeatherMap Account and Generate API Key
• Visit the OpenWeatherMap website (https://openweathermap.org/) and click on "Sign
Up" or "Log In" to create an account or log into your existing account.
• Once logged in, navigate to your account dashboard.
• From the dashboard, locate my API Keys section and click on "Create Key" or "API
Keys" to generate a new API key.
• Provide a name for your API key (e.g., "WeatherApp") and click on the "Generate" or
"Create" button.
• Your API key will be generated and displayed on the screen. Make sure to copy it as we
will need it later.
Step 2: Set up a new React project
• Open your terminal or command prompt.
• Run the following command to create a new React project:

• npxcreate-react-app weather-app
• Once the project is created, navigate into the project directory:

cd weather-app

Step 3: Install required packages


In the project directory, install the necessary packages by executing the following command

npm install axios


We will use the Axios library to make HTTP requests to the OpenWeatherMap API
Step 4: Create a Weather component
• Inside the "src" directory, create a new file called "Weather.js" and open it in your code
editor.

56
• Add the following code to define a functional component named Weather:
import React, { useState } from 'react';
importaxios from 'axios';
const Weather = () => {
const [city, setCity] = useState('');
const [weatherData, setWeatherData] = useState(null);

constfetchData = async () => {


try {
constapiKey = 'c97c0c1086d42990e89d64d76f50bb61'; // Replace with your OpenWeatherMap
API key
const response = await axios.get(

`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`
);
setWeatherData(response.data);
console.log(response.data); // You can see all the weather data in console log
} catch (error) {
console.error(error);
}
};

consthandleInputChange = (e) => {


setCity(e.target.value);
};

consthandleSubmit = (e) => {


e.preventDefault();
fetchData();
};
return (

57
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter city name"
value={city}
onChange={handleInputChange}
/>
<button type="submit">Get Weather</button>
</form>
{weatherData ? (
<>
<h2>{weatherData.name}</h2>
<p>Temperature: {weatherData.main.temp} °C</p>
<p>Description: {weatherData.weather[0].description}</p>
<p>Feels like: {weatherData.main.feels_like} °C</p>
<p>Humidity: {weatherData.main.humidity}%</p>
<p>Pressure: {weatherData.main.pressure} hPa</p>
<p>Wind Speed: {weatherData.wind.speed} m/s</p>
</>
):(
<p>Loading weather data...</p>
)}
</div>
);
};

export default Weather;


Step 5: Connect the Weather component to your app.
• Open the "App.js" file in the "src" directory.
• Replace the existing code with the following code:

58
import React from 'react';
import Weather from './Weather';
const App = () => {
return (
<div>
<h1>Weather Forecast App</h1>
<Weather />
</div>
);
};
export default App;

OUTPUT

59
60
Experiment 14

AIM: Create a TODO application in react with necessary components and deploy
it into github.

PROGRAM:

Step 1: Set Up the Project


Our first task is to set up the React project. This step involves creating the necessary project
structure. Here's how you can do it:
1. Create a React App:
Open your terminal and navigate to your preferred directory. Run the following command to
generate a new React app. Replace "todo-app" with your desired project name:

npx create-react-app todo-app

This command will create a directory named "todo-app" with all the initial code required for a
React app.
2. Navigate to the Project Directory:
Change your working directory to the "todo-app" folder:

cdtodo-app

3. Start the Development Server:


Launch the development server with the following command:

npm start
This will open your React app, and yousee the default React starter page in your web browser
at 'http://localhost:3000'.
Step 2: Create the App Component
import React from 'react';
importTodoList from './components/TodoList';
function App() {
return (
<div className="App">
<TodoList />

61
</div>
);
}
export default App;
Step 3: Create the TodoList
src->Component
Now, let's create the 'TodoList' component, which is responsible for managing the list of tasks and
handling task-related functionality.
import React, { useState } from 'react';
importTodoItem from './TodoItem';

functionTodoList() {
const [tasks, setTasks] = useState([
{
id: 1,
text: 'Doctor Appointment',
completed: true
},
{
id: 2,
text: 'Meeting at School',
completed: false
}
]);
const[text, setText] = useState('');
functionaddTask(text) {
constnewTask = {
id: Date.now(),
text,
completed: false
};

62
setTasks([...tasks, newTask]);
setText('');
}

functiondeleteTask(id) {
setTasks(tasks.filter(task => task.id !== id));
}

functiontoggleCompleted(id) {
setTasks(tasks.map(task => {
if (task.id === id) {
return { ...task, completed: !task.completed };
} else {
return task;
}
}));
}

return (
<div className="todo-list">
{tasks.map(task => (
<TodoItem
key={task.id}
task={task}
deleteTask={deleteTask}
toggleCompleted={toggleCompleted}
/>
))}
<input
value={text}
onChange={e =>setText(e.target.value)}

63
/>
<button onClick={() =>addTask(text)}>Add</button>
</div>
);
}
export default TodoList;
Step 4: Create the place the TodoItem in
src->Component
In this step, we create the 'TodoItem' component, which represents an individual task in our Todo
List.
import React from 'react';
functionTodoItem({ task, deleteTask, toggleCompleted }) {
functionhandleChange() {
toggleCompleted(task.id);
}

return (
<div className="todo-item">
<input
type="checkbox"
checked={task.completed}
onChange={handleChange}
/>
<p>{task.text}</p>
<button onClick={() =>deleteTask(task.id)}>
X
</button>
</div>
);
}

64
export default TodoItem;
Step 5: Styling
.todo-item {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
}

.todo-item p.completed {
color: #888;
text-decoration: line-through;
}

OUTPUT

Next,

65
VSCODE PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Todo List</title>
<style>
/* CSS Styles */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}

.container {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

input[type="text"] {
padding: 8px;

66
margin-right: 10px;
}

button {
padding: 8px 16px;
cursor: pointer;
}

ul {
list-style-type: none;
padding: 0;
}

li {
margin-bottom: 5px;
display: flex;
align-items: center;
opacity: 0;
animation: fadeIn 0.5s ease forwards;
}

.completed {
text-decoration: line-through;
transition: text-decoration 0.3s ease;
}

.checkbox {
margin-right: 10px;
}

.delete-btn {
margin-left: auto;
padding: 4px 8px;
background-color: #ff0000;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}

.delete-btn:hover {
background-color: #cc0000;
}

@keyframes fadeIn {

67
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
</head>
<body>
<div class="container">
<h1>Todo List</h1>
<input type="text" id="taskInput" placeholder="Enter task">
<button onclick="addTask()">Add</button>
<ul id="taskList"></ul>
</div>
<script>
// JavaScript Code
function addTask() {
const taskInput = document.getElementById('taskInput');
const taskList = document.getElementById('taskList');

const taskText = taskInput.value.trim();


if (taskText !== '') {
const newTask = document.createElement('li');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.classList.add('checkbox');

const taskLabel = document.createElement('label');


taskLabel.textContent = taskText;

const deleteBtn = document.createElement('button');


deleteBtn.textContent = 'Delete';
deleteBtn.classList.add('delete-btn');
deleteBtn.onclick = deleteTask;

newTask.appendChild(checkbox);
newTask.appendChild(taskLabel);
newTask.appendChild(deleteBtn);

newTask.onclick = toggleTask;
taskList.appendChild(newTask);
taskInput.value = '';

68
}
}

function toggleTask(event) {
if (event.target.tagName === 'INPUT') {
const checkbox = event.target;
const listItem = checkbox.parentNode;
listItem.classList.toggle('completed');
}
}

function deleteTask() {
const listItem = this.parentNode;
const taskList = listItem.parentNode;
taskList.removeChild(listItem);
}
</script>
</body>
</html>

OUTPUT

69
70

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy