Nodejs Lab Manual r22
Nodejs Lab Manual r22
For
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
COURSE STRUCTURE
(REGULATION:R22)
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
R22 B.Tech CSE SYLLABUS JNTU HYDERABAD
SKILL DEVELOPMENT COURSE (NODE JS/
REACT JS/ DJANGO)
B.Tech. II Year II Sem. L T P C
0 0 2 1
Prerequisites: Object Oriented Programming through Java, HTML Basics
Course Objectives:
● To implement the static web pages using HTML and do client side validation using JavaScript.
● To design and work with databases using Java
● To develop an end to end application using java full stack.
● To introduce Node JS implementation for server side programming.
● To experiment with single page application development using React.
Course Outcomes: At the end of the course, the student will be able to,
● Build a custom website with HTML, CSS, and Bootstrap and little JavaScript.
● Demonstrate Advanced features of JavaScript and learn about JDBC
● Develop Server – side implementation using Java technologies like
● Develop the server – side implementation using Node JS.
● Design a Single Page Application using React.
List of Experiments:
1. Build a responsive web application for shopping cart with registration, login, catalog
and cart pages using CSS3 features, flex and grid.
2. Make the above web application responsive web application using Bootstrap framework.
3. Use JavaScript for doing client – side validation of the pages implemented in
experiment 1 and experiment 2.
4. Explore the features of ES6 like arrow functions, callbacks, 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.
5. Develop a java stand alone application that connects with the database (Oracle /
mySql) and perform the CRUD operation on the database tables.
6. Create an xml for the bookstore. Validate the same using both DTD and XSD.
7. Design a controller with servlet that provides the interaction with application
developed inexperiment 1 and the database created in experiment 5.
8. Maintaining the transactional history of any user is very important. Explore the various
session tracking mechanism (Cookies, HTTP Session)
9. Create a custom server using http module and explore the other modules of Node JS
like OS, path, event.
10. Develop an express web application that can interact with REST API to perform
CRUDoperations on student data. (Use Postman)
11. For the above application create authorized end points using JWT (JSON Web Token).
12. Create a react application for the student management system having registration,
login, contact, about pages and implement routing to navigate through these pages.
13. Create a service in react that fetches the weather information from
openweathermap.org and the display the current and historical weather information
using graphical representation usingchart.js
14. Create a TODO application in react with necessary components and deploy it into github.
CO - PO MAPPING
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 3 3 3 3 - 2 3 3 2 2 3
CO2 3 3 3 3 3 2 - 3 3 - 2 3
CO3 3 3 3 3 3 - - 3 3 2 1 3
CO4 3 3 3 3 3 - - 3 3 - - 3
CO5 3 3 3 - 3 - - 3 3 - - 3
AVG 3 3 3 3 3 2 2 3 3 2 2 3
CO - PSO MAPPING:
PSO1 PSO2
CO1 - 2
CO2 - 2
CO3 - 1
CO4 - 2
CO5 - 1
AVG 0 2
SKILL DEVELOPMENT COURSE (NODE JS/ REACT JS/
DJANGO) LAB SYLABUS
(As Per R22 Syllabus Prescribed by JNTU, Hyderabad)
B.Tech II Year-II Sem (CSE)
LIST OF EXPERIMENTS
1.
Build a responsive web application for shopping cart with registration, login,
catalog and cart pages using CSS3 features, flex and grid.
2. Make the above web application responsive web application using Bootstrap
framework.
3. Use JavaScript for doing client – side validation of the pages implemented in
experiment 1 and experiment 2.
4.
Explore the features of ES6 like arrow functions, callbacks, 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.
5.
Develop a java stand alone application that connects with the database
(Oracle / mySql) and perform the CRUD operation on the database tables.
6. Create an xml for the bookstore. Validate the same using both DTD and XSD.
7.
Design a controller with servlet that provides the interaction with application
developed in experiment 1 and the database created in experiment 5.
8.
Maintaining the transactional history of any user is very important. Explore
the various session tracking mechanism (Cookies, HTTP Session).
9.
Create a custom server using http module and explore the other modules of
Node JS like OS, path, event.
10.
Develop an express web application that can interact with REST API to
perform CRUD operations on student data. (Use Postman).
11 For the above application create authorized end points using JWT (JSON Web
Token).
ADDITIONAL EXPERIMENTS
AIM: Build a responsive web application for shopping cart with registration, login, catalog and
cart pages using CSS3 features, flex and grid.
DESCRIPTION: HTML, CSS, and JavaScript are essential components for creating a
functional responsive web
application. A condensed example of a shopping cart with registration, login, catalogue, and cart
pages is provided.
Project Structure:
1. index.html - Main HTML file containing the structure of the web application.
2. styles.css - CSS file for styling the web pages.
3. script.js - JavaScript file for handling interactions and logic.
4. images/ - Folder for storing images.
index.html:
<!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>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="content">
<!-- Content will be loaded dynamically using JavaScript -->
</main>
<script src="script.js"></script>
</body>
</html>
——————————————
styles.css:
body {
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: #fff;
padding: 10px; text-
align: center;
}
nav ul {
list-style: none;
padding: 0;
display: flex;
justify-content: center;
}
nav li {
margin: 0 10px;
}
main {
padding: 20px;
}
/* Add more styles based on your design */
script.js:
// Dummy data for the catalog const
catalog = [
{ id: 1, name: 'Product 1', price: 20 },
{ id: 2, name: 'Product 2', price: 30 },
{ id: 3, name: 'Product 3', price: 25 },
];
// Function to load the catalog function
loadCatalog() {
const catalogContainer = document.getElementById('content');
catalogContainer.innerHTML = '<h2>Catalog</h2>'; catalog.forEach(product => {
const productCard = document.createElement('div');
productCard.classList.add('product-card');
productCard.innerHTML = `
<h3>${product.name}</h3>
<p>$${product.price}</p>
<button onclick="addToCart(${product.id})">Add to Cart</button>
`; catalogContainer.appendChild(productCard);
});
}
// Function to add a product to the cart function
addToCart(productId) {
// Implement cart functionality here
console.log(`Product ${productId} added to cart`);
}
// Initial load loadCatalog();
Explanation
1. HTML Structure: The HTML file consists of a header, navigation, and a main
content area, initially empty but dynamically populated using JavaScript.
2. CSS Styles: The CSS file offers basic styling for header, navigation, and main content
area, which can be customized according to your design needs.
3. JavaScript Logic: The JavaScript file contains dummy catalog data and functions
for loading and adding products to the cart, allowing real-world interaction with a ser
ver for catalog data retrieval and user cart management.
Output:
The shopping cart application's basic structure is displayed in index.html, with the catalog section
containing dummy product data.
Note: The example is intentionally simplified, and you would need to add more functionality,
such
as user authentication, cart management, and server communication, for a fully functional
shopping cart application.
EXPERIMENT- 2
AIM: Make the above web application responsive web application using Bootstrap
framework
DESCRIPTION:
Bootstrap is a popular CSS framework that makes it easy to create responsive web applications.
The previous example can be modified using Bootstrap by following these steps:
Project Structure:
1. index.html - Main HTML file containing the structure of the web application with
Bootstrap.
2. script.js - JavaScript file for handling interactions and logic (no changes from the
previous example).
3. styles.css - You can include additional custom styles if needed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/ bootstrap.min.css"
rel="stylesheet">
<!-- Custom CSS -->
<link rel="stylesheet" href="styles.css">
<title>Shopping Cart</title>
</head>
<body>
<header class="bg-dark text-white text-center py-3">
<h1>Shopping Cart</h1>
<nav>
<ul class="nav justify-content-center">
<li class="nav-item"><a class="nav-link" href="#catalog">Catalog</a></li>
<li class="nav-item"><a class="nav-link" href="#cart">Cart</a></li>
<li class="nav-item"><a class="nav-link" href="#login">Login</a></li>
<li class="nav-item"><a class="nav-link" href="#register">Register</a></li>
</ul>
</nav>
</header>
<main class="container mt-3" id="content">
<!-- Content will be loaded dynamically using JavaScript -->
</main>
<!-- Bootstrap JS (optional, for certain features) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/
bootstrap.bundle.min.js"></script>
<script src="script.js"></script>
</body>
</html>
styles.css:
/* You can include additional custom styles here if needed */ Explanation:
1. Bootstrap Integration: In the <head> section, we added links to the Bootstrap CSS and
JS files from a CDN (Content Delivery Network). This allows us to use Bootstrap's
styling and functionality.
3. Responsive Navigation: Bootstrap's grid system and utility classes help in creating a
responsive navigation bar. The justify-content-center class is used to center the
navigation links.
4. Responsive Main Content: The container class ensures that the main content area is
responsive. Bootstrap will automatically adjust the width based on the screen size.
Output:
When you open index.html in a web browser, you'll see that the web application is now
responsive.
The Bootstrap framework takes care of making the layout adapt to different screen sizes,
providing a more user-friendly experience on various devices.
Remember to test the responsiveness by resizing your browser or using different devices to
see how
the layout adjusts.
EXPERIMENT- 3
AIM: Use JavaScript for doing client – side validation of the pages implemented in experiment
1: Build a responsive web application for shopping cart with registration, login, catalog and cart
pages using CSS3 features, flex and grid and Experiment 2: Make the above web application
responsive web application using Bootstrap framework
DESCRIPTION: To perform client-side validation using JavaScript, you can add scripts to validate
user inputs on the registration and login pages.
The modifications for both experiments are listed below.
Explanation:
AIM: Explore the features of ES6 like arrow functions, callbacks, 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.
<!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>Weather Graph</title>
</head>
<body>
<div class="container">
<h1>Weather Graph</h1>
<canvas id="weatherGraph" width="400" height="200"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="script.js"></script>
</body>
</html>
————————————————————————————————-
styles.css:
body {
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
.container {
max-width: 600px; margin:
50px auto; background-
color: #fff; padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
}
canvas { display:
block;
margin: 20px auto;
}
script.js:
document.addEventListener('DOMContentLoaded', () => { const
apiKey = 'YOUR_OPENWEATHERMAP_API_KEY'; const city =
'YOUR_CITY_NAME';
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city} &appid=$
{apiKey}&units=metric`;
const fetchData = async () => { try {
const response = await axios.get(apiUrl); const
weatherData = response.data;
updateGraph(weatherData.main.temp);
} catch (error) {
console.error('Error fetching weather data:', error.message);
}
};
Explanation:
1. HTML Structure: We have a simple HTML structure with a container for the
graph canvas.
3. JavaScript (script.js):
• The fetchData function uses axios to make an asynchronous HTTP request to
OpenWeatherMap API.
• The retrieved weather data is used to update the graph using the
updateGraph function.
Output:
When you open index.html in a web browser, the application fetches the current weather information
for the specified city from OpenWeatherMap API and displays the temperature on a bar graph.
Please note that you need to replace 'YOUR_OPENWEATHERMAP_API_KEY' with your actual
API key. Additionally, the responsiveness and appearance can be further enhanced based on your
design preferences
EXPERIMENT- 5
AIM: Develop a java stand alone application that connects with the database (Oracle / mySql) and
perform the CRUD operation on the database tables.
DESCRIPTION: let's create a simple Java standalone application that connects to a MySQL
database and performs CRUD (Create, Read, Update, Delete) operations on a table. For this
example, we'll use JDBC (Java Database Connectivity) to interact with the MySQL
database.Prerequisites:
1. Make sure you have MySQL installed, and you know the database name,
username, and password.
2. Download the MySQL JDBC driver (JAR file) from MySQL Connector/J and
include it in your project.
import java.sql.*;
public class CRUD Example
{
// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/
your_database";
private static final String USERNAME = "your_username"; private
static final String PASSWORD = "your_password"; public static
void main(String[] args)
{
try {
// Step 1: Establishing a connection
Connection
connection=DriverManager.getConnection(JDBC_URL,USERNAME,
PASSWORD);
// Step 2: Creating a statement
Statement statement = connection.createStatement();
// Step 3: Performing CRUD operations
createRecord(statement, "John Doe", 50000);
readRecords(statement);
updateRecord(statement, 1, "John Updated", 55000); readRecords(statement);
deleteRecord(statement, 1);
readRecords(statement);
// Step 4: Closing resources
statement.close(); connection.close();
}
catch (SQLException e) {
e.printStackTrace();}
}
}
// Create a new record in the database
private static void createRecord(Statement statement, String name, int salary) throws
SQLException {
String insertQuery = "INSERT INTO employees (name, salary) VALUES ('" + name + "', " +
salary + “)";
statement.executeUpdate(insertQuery); System.out.println("Record
created successfully.");
}
// Read all records from the database
private static void readRecords(Statement statement) throws SQLException { String
selectQuery = "SELECT * FROM employees";
ResultSet resultSet = statement.executeQuery(selectQuery);
System.out.println("ID\tName\tSalary");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name"); int salary
= resultSet.getInt("salary");
System.out.println(id + "\t" + name + "\t" + salary);
}
System.out.println();
}
// Update a record in the database
private static void updateRecord(Statement statement, int id, String newName, int newSalary)
throws SQLException {
String updateQuery = "UPDATE employees SET name = '" + newName + "', salary = " +
newSalary + " WHERE id = " + id; statement.executeUpdate(updateQuery);
System.out.println("Record updated successfully.");
}
// Delete a record from the database
private static void deleteRecord(Statement statement, int id) throws SQLException {
String deleteQuery = "DELETE FROM employees WHERE id = " + id;
statement.executeUpdate(deleteQuery);
System.out.println("Record deleted successfully.");
}
}
Explanation:
1. Connection Parameters: Replace your_database, your_username, and
your_password with your actual database name, username, and password.
2.JDBC Connection: The getConnection method is used to establish a connection to the
MySQL database.
2. CRUD Operations:
• createRecord: Inserts a new record into the database.
• readRecords: Reads and prints all records from the database.
• updateRecord: Updates a record in the database.
• deleteRecord: Deletes a record from the database.
•
3. Output: The application prints the records before and after each operation,
showing the CRUD operations in action.
Output:
When you run this Java application, you should see output similar to the following in the console:
This demonstrates a simple Java standalone application for CRUD operations on a MySQL database
using JDBC. Keep in mind that for a production environment, you would want to use prepared
statements to prevent SQL injection and handle exceptions more gracefully
EXPERIMENT- 6
AIM: Create an xml for the bookstore. Validate the same using both DTD and XSD
DESCRIPTION: Let's create an XML file for a simple bookstore and validate it using both
Document Type Definition (DTD) and XML Schema Definition (XSD). Bookstore XML File
(bookstore.xml):
<?xml version="1.0" encoding=“UTF-8"?>
2. DTD File (bookstore.dtd): Describes the structure of the XML document using
Document Type Definition. Specifies that a bookstore must contain one or more book
elements. Each book must contain title, author, and price elements.
3. XSD File (bookstore.xsd): Describes the structure of the XML document using XML
Schema Definition. Defines complex types for bookstore and book. Specifies that a
bookstore must contain an unbounded sequence of book elements. Each book must
contain title (string), author (string), and price (decimal) elements.
Validation:
You can validate the XML file using a tool or programming language that supports DTD and XSD
validation. Here, I'll show you how to do it using a Java program. Java Program
for Validation:
import java.io.File;
import java.io.FileInputStream; import
java.io.IOException; import
java.io.InputStream; import
javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource; import
javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory; import
javax.xml.validation.Validator
import org.xml.sax.SAXException; public
class XMLValidator {
public static void main(String[] args) {
validateWithDTD("bookstore.xml", "bookstore.dtd");
validateWithXSD("bookstore.xml", "bookstore.xsd");
}
private static void validateWithDTD(String xmlFile, String dtdFile) { try {
InputStream xmlStream = new FileInputStream(new File(xmlFile));
InputStream dtdStream = new FileInputStream(new File(dtdFile));
SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.XML_DTD_NS_URI); Schema
schema = schemaFactory.newSchema(new StreamSource(dtdStream));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(xmlStream));
System.out.println("Validation with DTD successful.");
}
catch (SAXException | IOException e) {
System.out.println("Validation with DTD failed. Reason: " + e.getMessage());
}
}
private static void validateWithXSD(String xmlFile, String xsdFile) { try {
InputStream xmlStream = new FileInputStream(new File(xmlFile));
InputStream xsdStream = new FileInputStream(new File(xsdFile));
SchemaFactory schemaFactory =
Output:
If the XML file adheres to the specified DTD and XSD, you will see output messages like:
Validation with DTD successful.
Validation with XSD successful.
If there are issues with the XML file, the program will print error messages explaining the
validation failure.
Make sure to replace "bookstore.xml", "bookstore.dtd", and "bookstore.xsd" with the actual file
paths in your project. Also, you can use various online XML validators to validate your XML files
against DTD and XSD if you prefer a web- based approach.
EXPERIMENT- 7
AIM: Design a controller with servlet that provides the interaction with application developed in
experiment 1: Build a responsive web application for shopping cart with registration, login, catalog
and cart pages using CSS3 features, flex and grid and the database created in experiment 5: Develop
a java stand alone application that connects with the database (Oracle / mySql) and perform the
CRUD operation on the database tables
DESCRIPTION: To design a servlet controller that interacts with the shopping cart application
(Experiment 1) and thedatabase (Experiment 5), you would typically handle HTTP requests from
the web application, process the data, and communicate with the database to perform CRUD
operations.
This is a basic servlet controller example, but in a real-world scenario, additional security measures,
error handling, and Spring MVC frameworks may be needed.
Explanation:
1. Servlet Annotation (@WebServlet("/ShoppingCartController")): This annotation maps
the servlet to the specified URL pattern.
2. doPost Method: Handles HTTP POST requests. It checks the value of the "action"
parameter in the request and calls the appropriate method based on the action.
3. Action Methods (handleRegistration, handleLogin, handleAddToCart): Each method
handles a specific action requested by the client. It extracts data from the request,
performs the necessary logic (e.g., database operations), and sends a response back to the
client.
4. Error Handling: The controller checks for invalid actions or missing parameters and
sends an error response if necessary.
Note:
This example assumes that the web application sends HTTP POST requests to the servlet with an
"action" parameter to specify the desired operation.
Ensure that your web application sends requests to the correct URL pattern, in this case,
“/ShoppingCartController".
Make sure to handle exceptions properly, and consider using a connection pool for database connections
in a production environment.
This is a basic outline, and depending on your specific application requirements, you may need to
expand and customize these methods accordingly.
Output:
EXPERIMENT- 8
AIM: Maintaining the transactional history of any user is very important. Explore the various
session tracking mechanism (Cookies, HTTP Session)
DESCRIPTION: Session tracking mechanisms are crucial for maintaining the state of a user's
interactions with a web application. Two common methods for session tracking are Cookies and
HTTP Sessions.
1. Cookies: Cookies are small data pieces stored on a user's device by a web browser,
used to maintain user-specific information between the client and the server.
Example: Suppose you want to track the user's language preference. Server-side (in a
web server script, e.g., in Python with Flask):
from flask import Flask, request, render_template, make_response app = Flask(
name )
@app.route('/') def
index():
# Check if the language cookie is set
user_language = request.cookies.get('user_language')
return render_template('index.html', user_language=user_language)
@app.route('/set_language/<language>')
def set_language(language):
# Set the language preference in a cookie
response = make_response(render_template('set_language.html'))
response.set_cookie('user_language', language)
return response
Output:
When a user visits the site for the first time, the language preference is not set. When the user clicks
on "Set language to English" or "Set language to Spanish," the preference is stored in a cookie.
On subsequent visits, the site recognizes the user's language preference based on the cookie.
2. HTTP Session: An HTTP session is a way to store information on the server side
between requests from the same client. Each client gets a unique session ID, which is used
to retrieve session data.
Example: Suppose you want to track the number of visits for each user. Server-side (in
a web server script, e.g., in Python with Flask):
Output:
• Each time a user visits the site, the server increments the visit count stored in the
session.
• The visit count is unique to each user and persists across multiple requests until the
session expires.
These examples demonstrate simple use cases for cookies and HTTP sessions to maintain user-specific
information on the client and server sides, respectively.
EXPERIMENT- 9
AIM: Create a custom server using http module and explore the other modules of Node JS like OS,
path, event
DESCRIPTION:Let's create a simple custom server using the http module in Node.js and then
explore the os, path, and events modules with examples.
Explanation: -
Open Terminal or Command Prompt:
Open a terminal or command prompt in the directory where you saved your server.js file.
Run the Server Script:
Execute the server script using the Node.js runtime. In the terminal, run:
node server.js
This will start the HTTP server, and you should see the message "Server running at
http://127.0.0.1:3000/".
Access the Server:
Open your web browser and navigate to http://127.0.0.1:3000/ or http://localhost:3000/. You should see
the response "Hello, World!".
Check OS Information:
In the same terminal where your server is running, you'll see information about your operating system
(OS) type, platform, architecture, CPU cores, etc.
Check Current Working Directory:
The current working directory of the script is printed in the terminal.
Check Joined Path:
The joined path using the path module is printed in the terminal.
Open Terminal or Command Prompt:
Open a terminal or command prompt in the directory where you saved your server.js file.
Run the Server Script:
Execute the server script using the Node.js runtime. In the terminal, run:
node server.js
This will start the HTTP server, and you should see the message "Server running at
http://127.0.0.1:3000/".
Access the Server:
Open your web browser and navigate to http://127.0.0.1:3000/ or http://localhost:3000/. You should see
the response "Hello, World!".
Check OS Information:
In the same terminal where your server is running, you'll see information about your operating system
(OS) type, platform, architecture, CPU cores, etc.
Check Current Working Directory:
The current working directory of the script is printed in the terminal.
Check Joined Path:
The joined path using the path module is printed in the terminal.
Check Custom Event:
The script emits a custom event and listens for it. In the terminal, you should see the message "Custom
Event Triggered: { message: 'Hello from custom event!' }".
Stop the Server:
To stop the server, press Ctrl+C in the terminal where the server is running.
server.js
Output :
In the Terminal:
In the Browser:
Link: http://127.0.0.1:3000/
EXPERIMENT- 10
AIM: Develop an express web application that can interact with REST API to perform CRUD
operations on student data. (Use Postman)
Solution :
Firstly we need to create a new folder and open the folder in the command prompt and enter a
command as below:
npminit -y
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);
}
});
when we execute both the db.js then the database will be created that is mydatabase.db
app.js
const express = require('express');
const sqlite3 = require('sqlite3');
const{ initializeDatabase } = require('./db');
const app = express();
const port = 3000;
// 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 });
});
});
// 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.
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.
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.
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:
DESCRIPTION: To add JWT (JSON Web Token) authentication to your Express application,
you can use the jsonwebtoken package. Below are the steps to enhance the existing application with
authorized endpoints using JWT:
Aim: Create a react application for the student management system having registration, login, contact,
about pages and implement routing to navigate through these pages.
Description: Below is a step-by-step guide to create a simple React application for a student
management system with registration, login, contact, and about pages. We'll use react-router-dom
for routing.
This is a basic structure, and you can enhance it by adding functionality to the registration and login
forms, managing state, and connecting to a backend for data storage. Also, consider using react-router-
dom features like Switch, Redirect, and withRouter for more advanced routing scenarios.
EXPERIMENT- 13
AIM: Create a service in react that fetches the weather information from openweathermap.org and
the display the current and historical weather information using graphical representation using
chart.js
Solution :
npxcreate-react-app weather-app
cd weather-app
We will use the Axios library to make HTTP requests to the OpenWeatherMap API.
Inside the "src" directory, create a new file called "Weather.js" and open it in your code editor.
Add the following code to define a functional component named Weather:
Program:
try {
'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);
};
useEffect(() => {
fetchData();
}, []);
const handleInputChange = (e) => {
setCity(e.target.value);
};
e.preventDefault();
fetchData();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={city}
onChange={handleInputChange}
/>
</form>
{weatherData ? (
<>
<h2>{weatherData.name}</h2>
<p>Description: {weatherData.weather[0].description}</p>
<p>Humidity : {weatherData.main.humidity}%</p>
<p>Pressure : {weatherData.main.pressure}</p>
):(
)}
</div>
);
};
Output :
Initial Screen
After Supply the City name
EXPERIMENT- 14
AIM: Create a TODO application in react with necessary components and deploy it into github
Solution :
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:
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:
This command will create a directory named "todo-app" with all the initial code required for a React
app.
cd todo-app
npm start
This will open your React app, and you�ll see the default React starter page in your web browser
at 'http://localhost:3000'.
In this step, we create the App component, which serves as the entry point to our Todo List application.
import React from'react';
import TodoList from'./components/TodoList';
function App() {
return (
<div className="App">
<TodoList />
</div>
);
}
exportdefault App;
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';
import TodoItem from './TodoItem';
function TodoList() {
const [tasks, setTasks] = useState([
{
id: 1,
text: 'Doctor Appointment',
completed: true
},
{
id: 2,
text: 'Meeting at School',
completed: false
}
]);
src->Component
In this step, we create the 'TodoItem' component, which represents an individual task in our Todo List.
import React from'react';
function TodoItem({ task, deleteTask, toggleCompleted }) {
function handleChange() {
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>
);
}
exportdefault TodoItem;
These three components, 'App', 'TodoList', and 'TodoItem', work together to create a functional Todo
List application in React. The 'TodoList' component manages the state of the tasks, and the 'TodoItem'
component represents and handles individual tasks within the list.
Step 5: Styling
To enhance the visual appeal of your Todo List, you can apply some basic styling. Here s an example of
how you can style the todo items. In the `App.css` file, add the following styles:
.todo-item {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
}
.todo-itemp {
color: #888;
text-decoration: line-through;
}
Your output should look like this:
Output :
Initially it looks like:
Next,
ADDITIONAL EXPERIMENTS
EXPERIMENT- 15
DESCRIPTION: HTML, CSS are essential components for creating a functional responsive
web
Week.html
<!DOCTYPE html>
<html>
<head>
<title>Famous Book Store</title>
<!-- link css -->
<link href="main.css" rel="stylesheet">
</head>
<body>
<nav class="nav">
<div class="imglogo">
<img src= "images/fbs.png">
</div>
<h1>Famous Book Store</h1>
<ul class="menu">
<li><a href="Week7.html">Home</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="registration.html">Registration</a></li>
</ul>
</nav>
<section class="section bg">
<div class="divleft">
<img src="images/it-wp.jpg" class="thumbnail"></img>
</div>
<div class="divright">
<h1>Web Programming</h1>
<p>
SCRIPTING.
Web page Designing using HTML, Scripting basics- Client side and server side scripting.
Java Script-
Object, names, literals, operators and expressions- statements and features-
events - windows -
documents - frames - data types - built-in functions- Browser object model - Verifying
forms.-HTML5-
CSS3- HTML 5 canvas - Web site creation using tools.
</p>
</div>
</section>
<section class="section">
<div class="divright">
<h1>C Programming</h1>
<p>Introduction to Programming Introduction to components of a computer system: disks, primary
and secondary memory, processor, operating system, compilers, creating, compiling and executing a
program etc., Number systems Introduction to Algorithms: steps to solve logical and numerical
problems. Representation of Algorithm, Flowchart/Pseudo code with examples, Program design and
structured programming.
</p>
</div>
<div class="divleft">
<img src="images/cse-cp.jpg" class="thumbnail"></img>
</div>
</section>
<section class="section bg">
<div class="divleft">
<img src="images/cse-jp.jpg" class="thumbnail"></img>
</div>
<div class="divright">
<h1>Java Programming</h1>
<p>
Object-Oriented Thinking- A way of viewing world – Agents and Communities, messages and
methods, Responsibilities, Classes and Instances, Class Hierarchies- Inheritance, Method
binding,Overriding and Exceptions, Summary of Object-Oriented concepts. Java buzzwords, An
Overview of
Java, Data types, Variables and Arrays, operators, expressions, control statements, Introducing classes,
Methods and Classes, String handling.<br>
</p>
</div>
</section>
<footer>
<p>
Copyright © FBS -All rights are reserved
</p>
</footer>
</body>
</html>
login.html
<html>
<head>
<title> Welcome to FBS e-Book's website</title>
<!-- link css -->
<link href="main.css" rel="stylesheet">
</head>
<body >
<nav class="nav">
<div class="imglogo">
<img src= "images/fbs.png">
</div>
<h1>Famous Book Store</h1>
<ul class="menu">
<li><a href="Week7.html">Home</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="registration.html">Registration</a></li>
</ul>
</nav>
<section class="sectionlr bg">
<center><br>
<h3> Login Details</h3> <br/>
<form name="f1">
<table align="center" >
<tr>
<td> User Name : </td>
<td> <input type="text" name="username"></td>
</tr>
<tr><td><br></td></tr>
<tr>
<td> Password : </td>
<td> <input type="password" name="password"></td>
</tr>
<tr><td><br></td></tr>
<tr><td></td>
<td><input type="submit" value="SUBMIT" class="btn">
<input type="reset" value="RESET" class="rbtn"></td>
</tr>
</table>
</form>
</center>
</section>
<footer>
<p>
Copyright © FBS -All rights are reserved
</p>
</footer>
</body>
</html>
registration.html
<html>
<head>
<title> Welcome to FBS e-Book's website</title>
<!-- link css -->
<link href="main.css" rel="stylesheet">
</head>
<body>
<nav class="nav">
<div class="imglogo">
<img src= "images/fbs.png">
</div>
<h1>Famous Book Store</h1>
<ul class="menu">
<li><a href="Week7.html">Home</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="registration.html">Registration</a></li>
</ul>
</nav>
<form name="f1">
<table cellpadding="1" align="center" >
<tr><td> Name:*</td>
<td><input type="text" name="username"></td></tr>
<tr><td>Password:*</td>
<td><input type="password" name="password"></td></tr>
<tr><td>Email ID:*</td>
<td><input type="text" name="email"></td></tr>
<tr><td>Phone Number:*</td>
<td><input type="text" name="phno"></td></tr>
<tr><td valign="top">Gender:*</td>
<td><input type="radio" name="radio" value="1">Male
<input type="radio" name="radio" value="2">Female</td></tr>
<tr> <td valign="top">Language Known:*</td>
<td> <input type="checkbox" name="checkbox" value="English">English<br/>
<input type="checkbox" name="checkbox" value="Telugu">Telugu<br>
<input type="checkbox" name="checkbox" value="Hindi">Hindi<br>
<input type="checkbox" name="checkbox" value="Tamil">Tamil
</td></tr>
<tr> <td valign="top">Address:*</td>
<td><textarea name="address" rows="4" cols="22"></textarea></td>
<tr><td></td><td><input type="submit" value="SUBMIT" hspace="10" class="btn">
<input type="reset" value="RESET" class="rbtn"></td></tr>
<tr> <td colspan=2 >*<font color="#FF0000">fields are mandatory</font>
</td>
</tr>
</table>
</form>
</center>
</section>
<footer>
<p>
Copyright © FBS -All rights are reserved
</p>
</footer>
</body>
</html>
main.css
*{
font-family: 'verdana', serif; margin:
2px;
padding: 2px;
}
body {
padding:0px 200px;
}
.nav {
display: flex;
position: sticky; top:
0;
cursor: pointer; align-
items: center;
justify-content: center;
background: #fff;
background-size: cover;
}
.nav h1 {
color:#c936ab; font-
weight:italic; font-
size:40px;
padding-left:100px;
}
.imglogo { display:
flex;
justify-content: center;
align-items: center;
}
.imglogo img {
width: 120px;
border-radius: 20px;
}
.menu {
width: 40%;
display: flex;
justify-content: right;
}
.menu li {
list-style: none; padding:
25px 13px;
}
.menu li a {
font-size:20px;
text-decoration: bold; color:
black;
}
.menu li a:hover {
color: white;
background:#009933; padding:10px;
border-radius:20px; text-
decoration: none;
}
.section {
height: 160px;
display: flex;
align-items: center;
justify-content: center;
max-width: 90%; margin:
auto;
}
.sectionlr { height:
400px; display:
flex;
align-items: center;
justify-content: center;
max-width: 90%; margin:
auto;
}
.bg{
background:#99cccc;
}
.thumbnail {
width: 130px;
border: 2px solid black;
border-radius: 26px;
margin-top: 19px;
}
section {
padding:30px;
}
.divleft {
width:25%;
}
.divright { width:74%;
float:right;
}
p{
text-align:justify;
}
.btn {
padding:10px; background:#009900;
}
.rbtn {
padding:10px; background:#cc3333;
}
footer { margin:30px;
padding:30px;
color:white;
background:#0033ff;
}
footer p {
text-align:right;
}
Output:
EXPERIMENT- 16
AIM: Write an HTML page with Javascript that takes a number from one text field in the range
0-999 and display it in other text field in words.If the number is out of range ,it shold show “out
of range” and if it is not a number,it should show “not a number” message in the result box.
Conver.html
<script language="javascript">
function convert_number_to_words(number)
{
hyphen = '-';
conjunction = ' and ';
separator = ', ';
dictionary = {
0 : 'zero',
1 : 'one',
2 : 'two',
3 : 'three',
4 : 'four',
5 : 'five',
6 : 'six',
7 : 'seven',
8 : 'eight',
9 : 'nine',
10 : 'ten',
11 : 'eleven',
12 : 'twelve',
13 : 'thirteen',
14 : 'fourteen',
15 : 'fifteen',
16 : 'sixteen',
17 : 'seventeen',
18 : 'eighteen',
19 : 'nineteen',
20 : 'twenty',
30 : 'thirty',
40 : 'fourty',
50 : 'fifty',
60 : 'sixty',
70 : 'seventy',
80 : 'eighty',
90 : 'ninety',
100 : 'hundred',
};
if (number < 0 || number > 999)
{
alert("Enter a number range between 0 and 999");
return "";
}
switch (true)
{
case (number < 21):
string = dictionary[number];
break;
case (number < 100):
tens = parseInt(number / 10) * 10;
units = number % 10;
string = dictionary[tens];
if (units) {
string += hyphen + dictionary[units];
}
break;
case (number < 1000):
hundreds = parseInt(number / 100);
remainder = number % 100;
string = dictionary[hundreds] + ' ' + dictionary[100];
if (remainder) {
Output:
break;
case (number < 1000):
hundreds = parseInt(number / 100); remainder = number
% 100;
string = dictionary[hundreds] + ' ' + dictionary[100]; if
(remainder) {