0% found this document useful (0 votes)
14 views

Fsdl File Surajlab (2)

The document outlines two lab assignments focused on creating responsive websites for a fictional restaurant and a personal website. The assignments emphasize a mobile-first design approach, utilizing media queries to ensure compatibility across various devices and screen sizes. Key objectives include optimizing user experience, implementing fluid layouts, and ensuring accessibility while maintaining functionality across all platforms.

Uploaded by

surajyelpale7
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)
14 views

Fsdl File Surajlab (2)

The document outlines two lab assignments focused on creating responsive websites for a fictional restaurant and a personal website. The assignments emphasize a mobile-first design approach, utilizing media queries to ensure compatibility across various devices and screen sizes. Key objectives include optimizing user experience, implementing fluid layouts, and ensuring accessibility while maintaining functionality across all platforms.

Uploaded by

surajyelpale7
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/ 52

Name : Suraj Yelpale

Roll Number : D2223033

Lab Assignment-1
Problem statement- Create a responsive website for a fictional restaurant. The website
should display correctly on devices of various sizes, using media queries and a mobile first
design approach.

Objective-
● Design a Responsive Website: Create a website for a fictional restaurant that functions
well on various device sizes, including desktops, tablets, and smartphones.
● Implement Mobile-First Approach: Prioritize the design and functionality for mobile
devices first, ensuring a seamless user experience on smaller screens before adapting
for larger devices.
● Utilize Media Queries: Employ media queries to adjust layout, content, and functionality
according to different screen sizes and orientations.
● Ensure Cross-Device Compatibility: Verify that the website displays correctly and
maintains usability across a range of devices and screen resolutions.
● Optimize User Experience: Focus on delivering an engaging and intuitive experience for
users on all devices, with easy navigation and accessible information.

Theory- The primary objective of creating a responsive website is to ensure that users have a
consistent and optimized experience, whether they are accessing the site from a desktop
computer, tablet, or smartphone.
1. Mobile-First Design Approach: The mobile-first design approach advocates for designing
the website's core functionalities and layout for smaller screens first. This strategy
acknowledges the increasing use of mobile devices and ensures that the website is functional
and user-friendly on mobile devices before scaling up to larger screens. Key principles of this
approach include: Simplified Layout: Designing a straightforward and easy-to-navigate layout
that fits smaller screens and touch interfaces.
Progressive Enhancement: Starting with a basic version of the website and progressively
adding features and enhancements as the screen size increases.
2. Media Queries: Media queries are a critical tool in responsive web design. They allow
developers to apply different CSS styles based on the device’s characteristics, such as its
screen width, height, or orientation. By using media queries, the website can dynamically adjust
its layout and design to accommodate different screen sizes. Key aspects include:
Breakpoint Definition: Setting specific breakpoints where the design changes to accommodate
different screen sizes (e.g., mobile, tablet, desktop).
Flexible Layouts: Implementing fluid grids and flexible images that adapt to the screen size and
resolution.
3. Responsive Design Principles: Responsive web design encompasses several key
principles to ensure the website adapts effectively:

pg. 1
Name : Suraj Yelpale
Roll Number : D2223033

Fluid Grid Layouts: Using relative units (like percentages) instead of fixed units (like pixels) to
create a layout that adjusts fluidly to different screen sizes.
Flexible Images and Media: Ensuring that images and media elements scale appropriately and
do not exceed their container’s width, thereby preventing horizontal scrolling.
Adaptive Typography: Adjusting font sizes and line spacing to maintain readability across
various devices.
4. User Experience (UX) Optimization: A responsive website must also focus on optimizing
the user experience across different devices:
Touch-Friendly Design: Ensuring that interactive elements like buttons and links are large
enough and spaced adequately for touch interactions on mobile devices.
Content Prioritization: Displaying essential content prominently while potentially hiding or
simplifying less critical information on smaller screens.

Code- <!DOCTYPE html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Restaurant Website</title>
<style>
*{
box-sizing: border-box;
margin: 0; padding: 0;
}
body { font-family: Arial, sans-
serif ,italic; line-height: 1.6; background-
color: #f4f4f4; background-image:
url('https://d39l2hkdp2esp1.cloudfront.net/img/photo/213564/213564_00_2x.jpg?202007060733
27'); background-size:
cover; background-position:
center;
}
.overlay { background-color: rgba(128, 114,
114, 0.178); padding: 50px 0;
}
.container {
maxwidth: 1200px;
margin: 0 auto;
padding: 20px;
}
header { background-color: rgba(39, 44,
44, 0.774);
color: #fff; text-align:
center;

pg. 2
Name : Suraj Yelpale
Roll Number : D2223033

padding: 10px 0;
}
header h1 {
margin: 0; fontsize:
3em;
}
.menu { display:
flex; flex-wrap: wrap;
justify-content: center;
gap: 20px; margintop:
20px;
}
.menu-item { width: 300px;
background-color: #fff; border-radius:
5px; overflow: hidden; boxshadow:
0 0 10px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.menu-item:hover { transform:
translateY(-10px);
}
.menu-item img { width: 100%;
height: auto; border-bottom: 1px
solid #ccc;
}
.menu-item-info {
padding: 15px;
}
.menu-item h3 { margin-
top: 0; marginbottom: 10px;
font-size:
1.5em;
}
.menu-item p { margin-
bottom: 15px;
}
@media (max-width: 768px) {
.menu-item { width:
calc(50% - 20px);
}
}
@media (max-width: 480px) {
.menu-item { width:
100%;
}

pg. 3
Name : Suraj Yelpale
Roll Number : D2223033

}
</style>
</head>
<body>
<header>
<h1>Italian Flavors</h1>
</header>
<div class="overlay">
<div class="container">
<section class="menu">
<div class="menu-item">
<img src="https://recipes.net/wp-content/uploads/2023/05/cheesy-
alfredopastarecipe_5f653677c556b30cf4fb574861cabb03-768x768.jpeg" alt="Pasta">
<div class="menu-item-info">
<h3>Pasta</h3>
<p>fine flour of ground grain with water to create a dough and then making into
strips, ribbons and other shapes.</p>
<button onclick="addToCart('Food Item 1')">Add to Cart</button>
</div>
</div>
<div class="menu-item">
<img
src="https://images.ctfassets.net/nw5k25xfqsik/64VwvKFqxMWQORE10Tn8pY/200c0538099dc
4d1cf62fd07ce59c2af/20220211142754-margherita-9920.jpg" alt="Pizza">
<div class="menu-item-info">
<h3>Pizza</h3>
<p> Italian origin consisting of a flattened disk of bread dough topped with some
combination of olive oil, oregano, tomato, olives, mozzarella or other cheeseS</p>
<button onclick="addToCart('Food Item 2')">Add to Cart</button>
</div>
</div>
<div class="menu-item">
<img
src="https://www.eatingwell.com/thmb/rmLlvSjdnJCCy_7iqqj3x7XS72c=/1500x0/filters:no_upsc
ale():max_bytes(150000):strip_icc()/chopped-power-salad-with-chicken-
0ad93f1931524a679c0f8854d74e6e57.jpg" alt="Salad">
<div class="menu-item-info">
<h3>Salad</h3>
<p> green salad of romaine lettuce and croutons dressed with lemon juice, olive oil,
eggs, Worcestershire sauce, anchovies, garlic, Dijon mustard, Parmesan and black pepper</p>
<button onclick="addToCart('Food Item 2')">Add to Cart</button>
</div>
</div>
</section>

pg. 4
Name : Suraj Yelpale
Roll Number : D2223033

</div>
</div>
<script>
let cart = []; function
addToCart(itemName) {
cart.push(itemName); alert(`Added
${itemName} to cart!`);
}
</script>
</body> </html>

Output-

pg. 5
Name : Suraj Yelpale
Roll Number : D2223033

Conclusion- In summary, a mobile-first, responsive website for a fictional restaurant ensures


optimal performance and usability across all devices. By prioritizing mobile design and using
media queries, the site delivers a seamless experience for users on smartphones, tablets, and
desktops, enhancing engagement and accessibility.

pg. 6
Name : Suraj Yelpale
Roll Number : D2223033

Lab Assignment-2

Problem statement- Create a layout that uses media queries to adapt to different
screen sizes, ensuring your personal website is mobile-friendly

Objective- To design, develop, and implement a highly responsive layout for a


personal website that dynamically adjusts to various screen sizes, ensuring a seamless
and intuitive user experience across all devices. By utilizing CSS media queries, the
project aims to optimize the website's layout, including navigation, typography, images,
and overall structure, for both desktop and mobile platforms. The objective is to create a

mobile-friendly, visually appealing interface that maintains full functionality and


enhances accessibility, ensuring consistent performance and user satisfaction
regardless of device type or screen resolution.

Theory-
1. Understanding Media Queries

Media queries are a feature of CSS3 that allow developers to apply different styles to
different devices based on their characteristics, such as screen size, resolution, and
orientation. This technique is crucial for creating responsive web designs that adapt
seamlessly to various devices, ensuring that a website looks good and functions well on
screens of all sizes—from large desktop monitors to small mobile screens.

2. Importance of Responsive Design

With the increasing variety of devices used to access the web, a responsive design
ensures that your website is accessible and user-friendly on all devices. This improves
user experience, reduces bounce rates, and is essential for SEO, as search engines
like Google prioritize mobile-friendly websites.

3. Core Components of a Responsive Layout

Fluid Grid Layouts:

A fluid grid layout uses relative units like percentages instead of fixed units like pixels.
This allows elements on the webpage to resize in proportion to the screen size,
ensuring that the layout remains consistent across different devices.

pg. 7
Name : Suraj Yelpale
Roll Number : D2223033

Flexible Images:

Images should be able to resize according to the viewport. This can be achieved by
setting the image width to a percentage or using the max-width: 100%; rule in CSS. This
prevents images from overflowing their containers on smaller screens.

Media Queries:

Media queries are used to apply different CSS rules based on the device's
characteristics. For example, you might have one set of styles for screens wider than
1024px and another for screens narrower than 768px.

4. Breakpoints in Media Queries

Breakpoints are specific screen widths where the layout changes to accommodate
different devices. Common breakpoints might include:

Large screens (desktops): Widths above 1024px

Tablets: Widths between 768px and 1024px

Mobile phones: Widths below 768px

Code- Output-
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Adjustable Website</title>

<style>
*{

box-sizing: border-box; margin:

0; padding: 0;

pg. 8
Name : Suraj Yelpale
Roll Number : D2223033

body { font-family:

'Arial', sans-serif; line-height:

1.6; background-color: #f4f4f4; background-image:

url('https://w0.peakpx.com/wallpaper/115/408/HD-wallpapericebergminimalist.jpg'); background-

size: cover; background-position: center; color: #333;

header { background-color: rgba(39,

44, 44, 0.774);

color: #fff; text-align: center;

padding: 20px 0; box-shadow: 0 2px 5px

rgba(0, 0, 0, 0.2);

header h1 {
margin: 0;

font-size: 3em;

nav { margin:

20px 0; text-align:

center;

pg. 9
Name : Suraj Yelpale
Roll Number : D2223033

nav a { color: #fff;

text-decoration: none; margin:

0 15px; font-size:

1.2em; font-weight: bold; transition:

color 0.3s ease;

} nav

a:hover {

color: #f4f4f4;

.container { max-

width: 1200px; margin:

0 auto; padding: 20px;

.overlay { background-color: rgba(128,

114, 114, 0.178); padding: 50px 0;

display: none; transition: opacity 0.3s ease;

.overlay.active { display:

block;

pg. 10
Name : Suraj Yelpale
Roll Number : D2223033

.menu { display:

flex; flex-wrap: wrap;

justify-content: center;

gap: 20px;

.menu-item { width: 300px;

background-color: #fff; border-radius: 10px;

overflow: hidden; boxshadow: 0 0 15px

rgba(0, 0, 0, 0.2); transition: transform 0.3s

ease, box-shadow

0.3s ease;

.menu-item:hover { transform:

translateY(-10px); box-shadow: 0 0

25px rgba(0, 0, 0, 0.3);

.menu-item img { width:

100%; height: auto;

border-bottom: 1px solid #ddd;

pg. 11
Name : Suraj Yelpale
Roll Number : D2223033

.menu-item-info {

padding: 20px; textalign:

center;

.menu-item h3 {

margin-top: 0;

marginbottom: 15px;

fontsize: 1.8em; color:

#333;

}
.menu-item p {

margin-bottom: 15px; color:

#666;

button { backgroundcolor:

#39a7e1;

color: #fff; border: none;

padding: 10px 20px; border-radius:

5px; cursor: pointer; font-size: 1em;

transition: background-color 0.3s ease;

button:hover {

background-color: #297a9b;

pg. 12
Name : Suraj Yelpale
Roll Number : D2223033

form { background: #fff;

border-radius: 10px; padding: 20px;

box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);

} form

label {

display: block;

margin: 10px 0 5px;

font-weight: bold;

form input, form

textarea { width:

100%; padding: 10px;

margin-bottom: 15px;

border: 1px solid #ddd;

border-radius: 5px;

form button {

background-color: #39a7e1;

color: #fff; border: none;

padding: 10px 20px; border-radius:

5px; cursor: pointer; font-size:

1.2em; transition: background-color

0.3s ease;

pg. 13
Name : Suraj Yelpale
Roll Number : D2223033

}
form button:hover {

background-color: #297a9b;

@media (max-width: 768px) { .menu-

item { width:

calc(50% - 20px);

@media (max-width: 480px) { .menu-

item { width:

100%;

</style>

</head>

<body>

<header>

<h1>Adjustable Webpage</h1>

<nav>

<a href="#" onclick="showPage('home')">Home</a>

</nav>
</header>

pg. 14
Name : Suraj Yelpale
Roll Number : D2223033

<div id="home" class="overlay">

<div class="container">

<section class="menu">

<div class="menu-item">

<img src="https://encrypted-
tbn0.gstatic.com/images?q=tbn:ANd9GcSgqRFq42CuH2pXYFNKFjfx9qYax1ZDk_UPTqRVG3ZY2uredUx
XstwPQmGH-WD1xvBpts&usqp=CAU"

alt="image">

<div class="menu-item-info">

<h3>Image</h3>

</div>

</div>

</section>

</div>

</div>

<script>

let cart = [];

function

addToCart(itemNa

me) {

cart.push(itemNa

me);

alert(`Added

${itemName} to cart!`);

pg. 15
Name : Suraj Yelpale
Roll Number : D2223033

function showPage(pageId) {
document.querySelectorAll('.overlay').forEach(el => el.classList.remove('active'));

document.getElementById(pageId).classList.add('active');

showPage('home');

document.getElementById('orderform')?.addEventListener('submit', function (event)

{ event.preventDefault(); alert('Order submitted successfully!');

});

</script>

</body>

</html>

pg. 16
Name : Suraj Yelpale
Roll Number : D2223033

Conclusion- Incorporating media queries into your website's layout is crucial for
ensuring a mobile-friendly design. By adapting the layout to different screen sizes, you
enhance the user experience, making your site accessible and visually appealing
across a variety of devices. This approach not only improves usability but also
increases engagement by providing a seamless browsing experience, whether the user
is on a smartphone, tablet, or desktop. Through careful planning and implementation of
responsive design techniques, you can ensure that your personal website remains
functional and aesthetically pleasing, regardless of the device being used to access it.

pg. 17
Name : Suraj Yelpale
Roll Number : D2223033

Lab Experiment - 3

Objective:
Take a simple JavaScript project or exercises from the previous assignment and convert it into
TypeScript, focusing on adding types and interfaces.

JAVASCRIPT : CODE

– class

Calculator {

subtract(a, b) {

return a - b;

let calculator = new Calculator(); let result

= calculator.subtract(20, 8); console.log(`Subtraction

result: ${result}`);

TYPE SCRIPT : CODE- class Calculator {

subtract(a: number, b:

number): number {

return a - b;

}
let calculator = new Calculator(); let result: number

= calculator.subtract(10, 5);

console.log(`Subtraction result: ${result}`);

pg. 18
Name : Suraj Yelpale
Roll Number : D2223033

Output (Screenshots):
JavaScript:

TypeScript:

pg. 19
Name : Suraj Yelpale
Roll Number : D2223033

EXPERIMENT 04
AIM:
Develop a single-page application (SPA) using React.js that incorporates multiple components,
state management, and routing. Integrate with a public API to fetch and display dynamic data.

Theory:
React.js is a powerful JavaScript library for building user interfaces, particularly suited for
developing SPAs where content updates dynamically without requiring a full page reload. It
emphasizes the use of components, which are reusable and self-contained blocks of code that
represent parts of the user interface. React's virtual DOM efficiently updates the UI in response
to changes in state.

● Components:
Components are the building blocks of a React application. They can be functional or
class-based and are responsible for rendering parts of the UI. By managing their internal
state and accepting props, components can be composed together to create complex
interfaces.
● State Management:
React provides built-in hooks like useState for managing local component state. For
more complex applications, state management can be handled using useReducer
for centralized state logic or libraries like Redux for global state management across
the application.
● Routing:
React Router is used to implement navigation within the SPA, enabling the application to
switch views without refreshing the entire page. This creates a seamless user experience
where different sections of the app can be accessed through routes.
● API Integration:
Integration with public APIs is essential for fetching and displaying external data. React
allows easy integration using JavaScript's fetch API or libraries like Axios, making the
application dynamic and responsive to real-time data.

Technologies Used:

● HTML (Hypertext Markup Language):


HTML forms the backbone of web pages by providing the structure and content
organization. In a React application, JSX (JavaScript XML) is used, which allows HTML to
be written within JavaScript, making the code more readable and easier to maintain. ● CSS
(Cascading Style Sheets):
CSS is used to style the components and overall layout of the React application. SCSS
(Sassy CSS) can be employed for more advanced styling features, including variables,
nesting, and mixins, improving the maintainability and modularity of the styles.
○ Responsive Design:
Media queries in CSS ensure that the application adapts to different screen sizes,
providing an optimized experience across devices.
pg. 20
Name : Suraj Yelpale
Roll Number : D2223033

○ Theme Management:
CSS variables enable easy switching between light and dark themes, enhancing
the application's usability. React components can dynamically toggle these
themes based on user preferences.
○ Animations:
CSS transitions and keyframe animations can be utilized to create a smooth and
engaging user experience, making interactive elements more intuitive.
● JavaScript:
JavaScript, the core programming language for web development, is essential in React
applications for adding interactivity and handling dynamic content. JavaScript ES6+
features like arrow functions, destructuring, and async/await are extensively used in
modern React development.

Output (Screenshots):

pg. 21
Name : Suraj Yelpale
Roll Number : D2223033

pg. 22
Name : Suraj Yelpale
Roll Number : D2223033

ASSIGNMENT 5

AIM :- Build a RESTful API using Express.js that performs CRUD operations on a resource
(e.g., products, users). Include error handling and middleware for logging.

Objective

The objective of this project is to design and build a basic RESTful API using Express.js that can
perform CRUD operations (Create, Read, Update, Delete) on a chosen resource (e.g., products or
users). The API should demonstrate the following capabilities:

1. Implementing RESTful principles to structure endpoints that enable clients to perform


CRUD operations on resources.
2. Error handling to manage issues like invalid data inputs, non-existent resources, and
server errors, ensuring the API is robust and user-friendly.
3. Middleware for logging request details, enhancing the debugging process and providing
a clearer understanding of API usage patterns.
4. Practical demonstration of a Node.js environment, utilizing Express.js for routing and
basic server management, suitable for scalable web applications.

This project will serve as a foundational model for building more complex APIs and web services,
which can then be extended to include database integrations, user authentication, and deployment
in cloud environments.

CODE:-
server.js:
const express = require('express');
const morgan = require('morgan'); const
app = express();

// Middleware for parsing JSON requests


app.use(express.json());

// Logger middleware app.use(morgan('dev'));

// Sample data (product resource) let


products = [
{ id: 1, name: 'Product 1', price: 100 },

pg. 23
Name : Suraj Yelpale
Roll Number : D2223033

{ id: 2, name: 'Product 2', price: 150 }


];

// Create (POST) - Add a new product


app.post('/products', (req, res) => { const
product = req.body;
product.id = products.length + 1;
products.push(product); res.status(201).json(product); });

// Read (GET) - Get all products


app.get('/products', (req, res) => {
res.json(products);
});

// Read (GET) - Get a single product by ID


app.get('/products/:id', (req, res) => {
const productId = parseInt(req.params.id); const product =
products.find(p => p.id === productId); if (!product) return
res.status(404).json({ message: 'Product not found'
}); res.json(product);
});

// Update (PUT) - Update a product by ID


app.put('/products/:id', (req, res) => {
const productId = parseInt(req.params.id); const productIndex =
products.findIndex(p => p.id === productId); if (productIndex === -1)
return res.status(404).json({ message: 'Product not found' });
const updatedProduct = { ...products[productIndex], ...req.body };
products[productIndex] = updatedProduct;
res.json(updatedProduct);
});
// Delete (DELETE) - Delete a product by ID
app.delete('/products/:id', (req, res) => {
const productId = parseInt(req.params.id); const productIndex =
products.findIndex(p => p.id === productId); if (productIndex === -1)
return res.status(404).json({ message: 'Product not found' });
products.splice(productIndex, 1);
res.status(204).send();
});

// Error handling middleware app.use((err,


req, res, next) => {
console.error(err.stack); res.status(500).json({ message:
'Something went wrong!' });

pg. 24
Name : Suraj Yelpale
Roll Number : D2223033

});

// Start the server const PORT =


process.env.PORT || 3000; app.listen(PORT,
() => {
console.log(`Server running on http://localhost:${PORT}`); });

OUTPUT:-
Get:

POST:

pg. 25
Name : Suraj Yelpale
Roll Number : D2223033

PUT:

DELETE:

pg. 26
Name : Suraj Yelpale
Roll Number : D2223033

CONCLUSION:-
In conclusion, building a RESTful API with Express.js provides a robust foundation for handling
CRUD operations on resources efficiently. This project has highlighted key practices like error
handling and logging, ensuring smooth functionality and easier debugging.

pg. 27
Name : Suraj Yelpale
Roll Number : D2223033

ASSIGNMENT 6

AIM :- Create a basic server with Node.js and Express.js that serves your personal
website static files

Objective

The objective of this project is to create a basic server using Node.js and Express.js that can serve
static files for a personal website. This server should:

1. Serve HTML, CSS, and JavaScript files from a specified directory (e.g., /public) to
allow users to view the website in their browsers.
2. Demonstrate static file handling with Express middleware, enabling smooth access to
website resources like images and stylesheets.
3. Introduce fundamental server setup and configuration in Node.js, laying the
groundwork for more complex web applications.
4. Provide a responsive, accessible site that can be extended with dynamic features and
improved user experience over time.

This project offers a practical introduction to server-side development and deployment of a static
website.

CODE:-

Html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Personal Website</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
pg. 28
Name : Suraj Yelpale
Roll Number : D2223033

<p>Hi! I'm Himanshi Jagtap, a passionate learner and web developer.</p>


</header>
<main>
<section id="about">
<h2>About Me</h2>
<p>I am a beginner in web development, exploring the world of programming and design.
I enjoy learning new technologies and building creative projects.</p>
</section>
<section id="projects">
<h2>My Projects</h2>
<ul>
<li>Project 1: Coffe Shop Website</li>
<li>Project 2: Online Book Store</li>
<li>Project 3: Chat Bot</li>
</ul>
</section>

</main>
<footer>
<p>Contact me at: <a href="mailto:[email protected]">your-
[email protected]</a></p>
<p>&copy; 2024 [Himanshi Jagtap]</p>
</footer>
</body>
</html>

CSS:

/* Reset basic styles */


* { margin: 0; padding: 0; box-
sizing: border-box;
font-family: Arial, sans-serif;
}
/* Basic layout */ body {
display: flex; flexdirection:
column; minheight: 100vh;
backgroundcolor: #f4f4f9;
color:
#333;

pg. 29
Name : Suraj Yelpale
Roll Number : D2223033

}
/* Header styling */ header {
background-color: #4c99af;
color: white; padding: 20px;
text-align: center;
} header h1 { marginbottom: 10px;

}
/* Main content styling */ main
{ flex: 1; padding: 20px;
} section { margin-
bottom: 20px;
} h2 { color: hsl(12, 39%,
49%); margin-bottom: 10px;
}
/* Footer styling */ footer
{ background-color: #333;
color: white; text-align:
center; padding: 10px;
} footer a { color: hsl(115, 39%,
49%); text-decoration:
none;
} footer a:hover {
text-decoration: underline; }

Server.js:
// server.js const express =
require('express'); const path =
require('path');

pg. 30
Name : Suraj Yelpale
Roll Number : D2223033

const app = express(); const PORT =


process.env.PORT || 3000;
// Serve static files from the 'public' directory
app.use(express.static(path.join( dirname, 'public')));
// Define a route for the root URL that serves the index.html file
app.get('/', (req, res) => { res.sendFile(path.join( dirname,
'public', 'index.html')); });
// Start the server app.listen(PORT, () => { console.log(`Server
is running on http://localhost:${PORT}`); });

OUTPUT:-

CONCLUSION:-

In conclusion, setting up a basic server with Node.js and Express.js to serve static files
effectively demonstrates core server-side principles for deploying a personal website. This
project showcases how to configure Express to handle static assets, providing a responsive user
experience.

pg. 31
Name : Suraj Yelpale
Roll Number : D2223033

AIM: ASSIGNMENT 7
Building a simple Restful API with Node.js ,Express.js and MongoDB for cloud computing
applications

OBJECTIVE:
A RESTful API (Representational State Transfer) is an architectural style for designing
networked applications, often used for web services. It allows interaction with server
resources using standard HTTP methods like GET, POST, PUT, and DELETE. RESTful APIs are
popular for building cloud computing applications due to their scalability, simplicity, and
compatibility with modern web and mobile applications.
1. Node.js
• Node.js is a JavaScript runtime built on Chrome’s V8 engine, allowing developers to
write server-side applications in JavaScript. It’s designed to be event-driven and non-
blocking, making it efficient and suitable for scalable network applications.
• In this experiment, Node.js serves as the foundation of our API, handling requests and
managing the application's overall flow.
2. Express.js
• Express.js is a lightweight and flexible web application framework for Node.js. It
simplifies the process of creating and handling HTTP requests, defining routes, and
managing middleware.
• For this API, Express allows us to create endpoints, manage URL routing, and
implement RESTful operations (CRUD—Create, Read, Update, Delete) for different
resources.
3. MongoDB
• MongoDB is a NoSQL database, ideal for cloud applications due to its flexibility,
scalability, and document-oriented structure. It stores data in JSON-like documents,
making it well-suited for handling large and unstructured datasets commonly found in
cloud applications.
• MongoDB will store our data entities, which we access and manipulate using
Mongoose, an Object Data Modeling (ODM) library for MongoDB in Node.js.
Mongoose provides a schema-based solution, allowing us to define and enforce data
structures for consistent storage and retrieval.
4. Mongoose
• Mongoose is an ODM library for MongoDB and Node.js, enabling a more structured
approach to managing MongoDB documents. It provides schema definitions for data
validation, query-building capabilities, and helpful middleware to handle asynchronous
operations smoothly.
• Using Mongoose, we can create models that map to MongoDB collections, and we can
interact with these models to perform CRUD operations.
5. Architecture and Design

pg. 32
Name : Suraj Yelpale
Roll Number : D2223033

• In RESTful API architecture, each resource (e.g., User, Product) is represented by a URI
(Uniform Resource Identifier) and is accessible via HTTP methods:
o GET retrieves data, o POST
creates data, o PUT/PATCH
updates data, o
DELETE removes data.
• By following REST principles, the API remains stateless and adheres to standard
conventions, enhancing compatibility and making it easier to scale and deploy in a
cloud environment.
6. Middleware and Error Handling
• Middleware functions in Express.js handle additional tasks like parsing JSON data,
validating requests, and managing authentication. Middleware can be customized to
enforce security measures, handle errors, and log requests, which is essential for
cloud-based applications.
• Error handling ensures that the API gracefully manages and communicates issues,
whether due to client requests or server errors, providing users with helpful feedback.
7. Deployment in Cloud Environment
• Deploying a RESTful API to the cloud offers benefits like scalability, data replication,
load balancing, and high availability.
• Cloud platforms like AWS, Heroku, or Google Cloud Platform provide tools to deploy
Node.js applications and integrate with managed MongoDB services. This setup
ensures that our API can handle increasing user loads, maintain high performance, and
store data securely.

Output:

pg. 33
Name : Suraj Yelpale
Roll Number : D2223033

pg. 34
Name : Suraj Yelpale
Roll Number : D2223033

ASSIGNMENT 8

AIM:-
Develop a simple RESTful API with Express.js that performs CRUD operations on an array of
objects (e.g., blog posts, user profiles).

OBJECTIVE:-
The objective of this project is to build a simple RESTful API using Express.js that performs
CRUD operations (Create, Read, Update, Delete) on an in-memory array of objects, such as blog
posts or user profiles. This project aims to:

1. Implement RESTful endpoints to manage resources by enabling operations to add,


retrieve, update, and delete items.
2. Reinforce understanding of HTTP methods (POST, GET, PUT, DELETE) and how they
map to CRUD operations in a server environment.
3. Apply error handling and validation to ensure reliable responses and prevent issues, such
as invalid data or non-existent entries.
4. Introduce middleware for parsing JSON and logging requests, enhancing development
experience and maintaining clean code structure.
5. Lay the groundwork for connecting to databases in future projects by establishing basic
CRUD logic that can easily extend to persistent storage.

A RESTful API (Representational State Transfer) is an architectural style that allows applications
to communicate over the web. It is widely used for building APIs because it provides a
standardized way for clients (like browsers or mobile apps) to interact with servers using HTTP
methods. CRUD operations (Create, Read, Update, Delete) are fundamental actions that allow
users to manage resources within an application. In this project, we'll use Express.js, a lightweight
and flexible Node.js framework, to create a RESTful API that performs CRUD operations on an
array of objects.

Key Concepts:

1. HTTP Methods: o POST: Used to create a new resource. o GET: Used to retrieve data or a
list of resources. o PUT: Used to update an existing resource.
o DELETE: Used to delete a resource.

These HTTP methods map directly to CRUD operations and help define RESTful endpoints
in a standardized way.
2. Express.js:
pg. 35
Name : Suraj Yelpale
Roll Number : D2223033

o Express.js is a popular Node.js framework that simplifies routing and handling requests and
responses. It allows developers to define endpoints (routes) and associate them with specific
functions (controllers) to manage the API’s functionality.
3. In-Memory Array:
o An in-memory array stores objects like blog posts or user profiles within the server’s
memory. This makes CRUD operations fast but temporary, as the data is erased when the
server restarts. This approach is useful for testing and prototyping APIs.
4. Middleware:
o Middleware in Express.js intercepts requests and can perform actions like logging, parsing,
or validating data before reaching the endpoint logic. JSON parsing middleware allows
the server to understand JSON data, while logging middleware helps monitor request
information for debugging and analysis.
5. Error Handling:
o Error handling is crucial in API development to ensure stability and usability. Proper error
handling catches and responds to issues like invalid inputs or requests for non-existent
resources, providing users with informative feedback instead of crashes or undefined
behavior.
6. Endpoint Structure:
o A well-designed RESTful API uses clear and consistent endpoint names. For example, /posts
can represent a list of blog posts:
▪ GET /posts: Fetch all posts.
▪ POST /posts: Add a new post.
▪ GET /posts/:id: Fetch a specific post by ID.
▪ PUT /posts/:id: Update a specific post by ID.

Benefits of RESTful APIs with CRUD Operations:

• Standardized Structure: RESTful APIs provide a uniform structure, making it easier to understand
and use.
• Scalability: RESTful APIs can be scaled to handle more complex functionality, including database
integrations, user authentication, and secure handling of sensitive data.
• Reusability: The API design can be used across different applications, such as web and mobile
apps, promoting code reuse and simplifying future development.

CODE:-
Index.js

pg. 36
Name : Suraj Yelpale
Roll Number : D2223033

const express = require('express'); const


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

// Middleware to parse JSON bodies app.use(bodyParser.json());

// Sample data array to store blog posts let posts


= [
{ id: 1, title: 'First Post', content: 'This is the first blog post.' },
{ id: 2, title: 'Second Post', content: 'This is the second blog post.'
},
];

// Helper function to find a post by ID const findPostById = (id)


=> posts.find((post) => post.id === id);
// CREATE a new post app.post('/posts',
(req, res) => { const { title, content
} = req.body; const newPost = { id:
posts.length + 1, title, content,
}; posts.push(newPost); res.status(201).json(newPost);

pg. 37
Name : Suraj Yelpale
Roll Number : D2223033

});

// READ all posts


app.get('/posts', (req, res) =>
{ res.json(posts); });

// READ a single post by ID


app.get('/posts/:id', (req, res) => {
const postId = parseInt(req.params.id);
const post = findPostById(postId); if
(post) { res.json(post);
} else { res.status(404).json({ message: 'Post not found' });
}
});

// UPDATE a post by ID
app.put('/posts/:id', (req, res) => { const
postId = parseInt(req.params.id); const {
title, content } = req.body; const post =
findPostById(postId);

if (post) { post.title = title ||


post.title; post.content = content ||
post.content; res.json(post);
} else { res.status(404).json({ message: 'Post not found' });
} });

// DELETE a post by ID app.delete('/posts/:id',


(req, res) => { const postId = parseInt(req.params.id); const
postIndex = posts.findIndex((post) => post.id === postId);

if (postIndex !== -1) { posts.splice(postIndex,


1);

pg. 38
Name : Suraj Yelpale
Roll Number : D2223033

res.status(204).send();
} else { res.status(404).json({ message: 'Post not found'
}); }
});
// Start the server app.listen(PORT, () => { console.log(`Server is
running on http://localhost:${PORT}`); });

Output:

PUT:

GET:

pg. 39
Name : Suraj Yelpale
Roll Number : D2223033

CONCLUSION:-
In conclusion, developing a simple RESTful API with Express.js for CRUD operations on an
array of objects provides valuable insights into building and managing server-side applications.
Through this project, we have successfully set up structured routes for each operation,
implemented essential error handling, and leveraged middleware for request parsing and logging.
This foundational API can easily extend to support databases, authentication, and advanced
routing, making it a versatile starting point for developing scalable backend services.

pg. 40
Name : Suraj Yelpale
Roll Number : D2223033

EXPERIMENT 09
AIM:
Connect your Express.js application to a PostgreSQL or MongoDB database and modify your API
to perform CRUD operations on the database.

OBJECTIVE:
In modern web applications, databases like PostgreSQL and MongoDB serve as the backend
storage systems for data. By connecting an Express.js application to a database, we enable
dynamic, persistent storage for the application’s resources. CRUD operations allow the API to
create, retrieve, update, and delete data entries, providing a full suite of functionality to interact
with the database.
1. Choosing a Database
• PostgreSQL: A relational database management system (RDBMS) known for its
robustness, ACID compliance, and support for SQL queries. It is ideal for applications
requiring complex querying, structured data relationships, and data integrity.
• MongoDB: A NoSQL document-oriented database that stores data in JSON-like
documents. It offers flexibility, scalability, and is well-suited for applications with
unstructured data or rapidly changing schemas.
2. Connecting to the Database • PostgreSQL:
o Connect to PostgreSQL using a Node.js client library such as pg. This library allows
Express.js to run SQL queries on the PostgreSQL database. o Define connection
parameters, including database URL, username, password, and host information.
• MongoDB:
o Connect to MongoDB using Mongoose, an Object Data Modeling (ODM) library
that simplifies database interactions.
o Mongoose allows defining schemas and models to structure data and provide an
interface to perform CRUD operations on MongoDB documents.
3. Defining Models or Schemas
• PostgreSQL: Uses tables, so models are created based on table structures. Each table
defines columns, data types, and constraints.
• MongoDB: Uses collections, where each document can follow a flexible schema. With
Mongoose, schemas define the structure of documents in a collection, making data
validation easier.
4. Implementing CRUD Operations
• Create: Adds new entries to the database.
o PostgreSQL: Use SQL INSERT statements to add rows to a table. o MongoDB: Use
model.create() to add a document to a collection.
• Read: Retrieves data from the database.
o PostgreSQL: Use SQL SELECT statements to query rows based on criteria.
o MongoDB: Use model.find() to fetch documents from a collection.
• Update: Modifies existing entries in the database.
o PostgreSQL: Use SQL UPDATE statements to modify data in specific rows.
pg. 41
Name : Suraj Yelpale
Roll Number : D2223033

o MongoDB: Use model.findByIdAndUpdate() to update a document.


• Delete: Removes entries from the database.
o PostgreSQL: Use SQL DELETE statements to remove rows.
o MongoDB: Use model.findByIdAndDelete() to delete documents.
5. Routes and Controllers in Express.js
• In a RESTful API, each route corresponds to a specific HTTP method and path (e.g., /users
for user data).
• Each route connects to a controller function that performs CRUD operations on the
database:
o POST /users: Creates a new user. o GET /users: Retrieves a list of users.
o GET /users/
: Retrieves a specific user by ID. o
PUT /users/
: Updates an existing user.
o DELETE /users/
: Deletes a user.
6. Benefits of Database Integration in Express.js Applications
• Persistence: Data remains available across sessions and application restarts.
• Scalability: Databases are optimized for handling large datasets and support concurrent
requests.
• Data Management: Using CRUD operations provides complete control over data,
enabling applications to dynamically interact with and modify stored information.
7. Security and Error Handling
• Implement security best practices such as input validation, parameterized queries (to
prevent SQL injection in PostgreSQL), and schema validation (especially in MongoDB).
• Error handling is crucial for managing failed database connections or invalid queries.
Express can handle errors using middleware, providing user-friendly messages when
operations fail.
Code:
1. app.js:

const express = require('express'); const


mongoose =
require('mongoose'); const morgan =
require('morgan'); const
bodyParser =

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

express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true, useUnifiedTopology:
true
}).then(() => { console.log('MongoDB connected');
pg. 42
Name : Suraj Yelpale
Roll Number : D2223033

}).catch(err => console.log('Database connection error:', err));

// Middleware app.use(morgan('dev'));
app.use(bodyParser.json()
);

// Start the server


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

const productRoutes = require('./routes/products'); app.use('/api/products',


productRoutes);

app.use((err, req, res, next) => {


console.error(err.stack); res.status(500).json({
message: 'An error occurred!' });
});

2. routes/products.js:

const express =
require('express'); const router = express.Router();
const Product = require('../models/Product');

// Create a Product (POST)


router.post('/', async (req, res) =>
{ try {
const product = new Product(req.body); const
savedProduct = await
product.save();
res.status(201).json(savedProduct);
} catch (error) { res.status(400).json({ message:
error.message });
}
});

// Get All Products (GET)


router.get('/', async (req, res) =>
{ try {
const products = await Product.find(); res.json(products);
} catch (error) { res.status(500).json({ message:
error.message });
}
});
pg. 43
Name : Suraj Yelpale
Roll Number : D2223033

// Get Single Product (GET) router.get('/:id', async


(req, res) =>
{ try {
const product = await Product.findById(req.params.id);
if (!product) return res.status(404).json({ message: 'Product not found' });
res.json(product);
} catch (error) { res.status(500).json({ message:
error.message });
}
});
// Update a Product (PUT)
router.put('/:id', async (req, res) =>
{ try {

pg. 44
Name : Suraj Yelpale
Roll Number : D2223033

const updatedProduct = await Product.findByIdAndUpdate(req.params.id,


req.body, { new: true }); if (!updatedProduct) return res.status(404).json({ message:
'Product not found'
}); res.json(updatedProduct);
} catch (error) { res.status(400).json({
message:error.message });
}
});
// Delete a Product (DELETE)
router.delete('/:id', async (req, res) =>
{ try {
const deletedProduct = await Product.findByIdAndDelete(req.params.id); if
(!deletedProduct) return res.status(404).json({ message: 'Product not found' });
res.json({ message: 'Product deleted' });
} catch (error) { res.status(500).json({ message:
error.message });
}
});
module.exports = router;

3. models/Product.js: // models/Product.js
const mongoose = require('mongoose');

const productSchema = new


mongoose.Schema({ name: { type: String, required:
true },
price: { type: Number, required: true }, description:
String,
});

module.exports = mongoose.model('Product', productSchema); Output:

pg. 45
Name : Suraj Yelpale
Roll Number : D2223033

pg. 46
Name : Suraj Yelpale
Roll Number : D2223033

Conclusion:
By connecting your Express.js application to MongoDB and modifying the API to perform
CRUD operations, you’ve established a scalable and flexible data management system.
MongoDB, with its schema-less NoSQL nature, allows your application to handle dynamic and
unstructured data efficiently. This integration enables you to store, retrieve, update, and
delete data seamlessly, enhancing your application's functionality. MongoDB’s scalability and
ease of use make it an ideal choice for web applications, especially as they grow. This setup

pg. 47
Name : Suraj Yelpale
Roll Number : D2223033

ensures that your API can handle real-world data-driven use cases effectively, providing a solid
foundation for building modern, data-centric applications.

EXPERIMENT 10

AIM:
Implement JWT-based authentication for your API, allowing users to sign up, log in, and access
protected routes.

OBJECTIVE:

1. Express.js Setup:
• Definition: Express.js is a minimal and flexible Node.js web application framework. It
provides routing and middleware functionality.
• Usage in Code: The application is created using express(), and app.use(express.json())
enables parsing of incoming JSON data in request bodies, necessary for handling user
credentials.
2. JWT (JSON Web Token):
• Purpose: JWT is used to securely transmit information between two parties (e.g., client
and server) as a JSON object. The token ensures data integrity by allowing the server to
verify the client’s authenticity without needing to store session data.
• Usage in Code: The jsonwebtoken library is used to create and verify JWTs. Tokens are
signed with a secret key (JWT_SECRET) and contain encoded user information, allowing
the server to verify users on subsequent requests.
3. User Registration Endpoint (POST /register):
• Purpose: This endpoint allows new users to sign up by providing a username and
password.
• Implementation:
o Data Handling: The code checks if a user with the same username already exists
by looking through the users array.
o Error Handling: If a user exists, it sends a 400 error with a relevant message.
Otherwise, it stores the new user and returns a success message.
4. User Login Endpoint (POST /login):
• Purpose: Allows users to log in with their credentials to receive a JWT.
• Implementation:
o Authentication: The endpoint checks if a user with the given username and
password exists in the users array.
o Token Generation: If the credentials are valid, a JWT is generated using jwt.sign().
The payload includes the username, and the token expires after 1 hour (expiresIn:
'1h'). o Response: The token is sent back to the client, which can use it to access
protected resources.
5. JWT-Based Authentication Middleware (authenticateToken):

pg. 48
Name : Suraj Yelpale
Roll Number : D2223033

• Purpose: Middleware functions are used to protect routes by verifying JWTs. It checks if
the token in the request is valid.
• Implementation:
o Token Extraction: The token is expected in the Authorization header in the format
Bearer <token>.
o Token Verification: The middleware uses jwt.verify() to decode and verify the
token using the secret key (JWT_SECRET). o Error Handling: If the token is missing
or invalid, a 401 or 403 response is sent, denying access to protected routes.
6. Protected Route (GET /profile):
• Purpose: This endpoint represents a protected route that only authenticated users can
access.
• Implementation: The authenticateToken middleware checks the token before the route
handler is executed. If the token is valid, the user’s data from the token payload (such as
username) is accessible and returned in the response.

Code:

pg. 49
Name : Suraj Yelpale
Roll Number : D2223033

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


require('jsonwebtoken');const app =
express(); app.use(express.json());

const JWT_SECRET = "your_jwt_secret_key";const

users = [];

app.post('/register', (req, res) => { const { username, password } =


req.body;

const existingUser = users.find(user => user.username === username);if


(existingUser)
{
return res.status(400).json({ message: "User already exists" });
}

users.push({ username, password }); res.status(201).json({


message: "User registered successfully" });
});

app.post('/login', (req, res) => { const { username,


password } = req.body;

const user = users.find(u => u.username === username && u.password


=== password);if
(!user) { return res.status(400).json({ message: "Invalid credentials" });
}

const token = jwt.sign({ username: user.username }, JWT_SECRET, {expiresIn:


'1h'
});
res.json({ token });
});

Output:

API testing and Validation using POSTMAN

pg. 50
Name : Suraj Yelpale
Roll Number : D2223033

1) Register a User (POST/ register)

2) Login a User (POST/ login)

3) Validate or Authenticate the user (GET/profile)

pg. 51
Name : Suraj Yelpale
Roll Number : D2223033

Conclusion:
This JWT-based authentication system provides a secure and efficient way to manage user
access in an Express.js application. By using JSON Web Tokens, the system allows for stateless
authentication, meaning the server doesn’t need to store session data, making it ideal for
scalable applications. The setup ensures that only authenticated users can access protected
routes, enhancing security and flexibility. This approach is well-suited for cloud-based or
distributed applications where managing sessions can be challenging, offering a streamlined
method for handling user authentication and access control.

pg. 52

You might also like