0% found this document useful (0 votes)
10 views25 pages

Experiment 11 To 14

The document outlines the creation of an Express.js application with JWT-based authentication for user login and protected endpoints, followed by a React application for a student management system with routing for various pages. It details the steps for setting up both applications, including necessary packages, middleware for JWT verification, and the structure of the React components. Additionally, it describes a service to fetch weather data from OpenWeatherMap and visualize it using Chart.js.

Uploaded by

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

Experiment 11 To 14

The document outlines the creation of an Express.js application with JWT-based authentication for user login and protected endpoints, followed by a React application for a student management system with routing for various pages. It details the steps for setting up both applications, including necessary packages, middleware for JWT verification, and the structure of the React components. Additionally, it describes a service to fetch weather data from OpenWeatherMap and visualize it using Chart.js.

Uploaded by

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

EXPERIMENT: 11

1. For the above application create authorized end points using JWT (JSON Web
Token).

To create authorized endpoints using JSON Web Token (JWT), you'll need to add user
authentication and authorization functionality to your Express.js application. This
involves several steps: creating user login endpoints, generating JWT tokens, verifying
tokens on protected routes, and handling token expiration.

Step 1: Install Required Packages


First, install the necessary packages for JWT-based authentication:
npm install jsonwebtoken bcryptjs

jsonwebtoken: A package to generate and verify JWT tokens.


bcryptjs: A package to hash and compare passwords for secure user authentication.
Step 2: Set Up User Authentication and JWT Generation
In this step, create an endpoint for user login, where a JWT token is generated upon
successful authentication.
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
const PORT = 3000;

// Secret key for JWT signing


const JWT_SECRET = 'mySecretKey';

// Middleware to parse JSON bodies


app.use(express.json());

// Sample user data with hashed passwords (in a real application, this would be stored in a
database)
const users = [
{
id: 1,
username: 'admin',
password: bcrypt.hashSync('adminpass', 10), // Hashed password
},
];

// User login endpoint


app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find((u) => u.username === username);

if (!user) {
return res.status(401).json({ message: 'Invalid username or password' });
}

const passwordValid = bcrypt.compareSync(password, user.password);

if (!passwordValid) {
return res.status(401).json({ message: 'Invalid username or password' });
}

// Create JWT token with a payload containing user information


const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET,
{ expiresIn: '1h' });

res.status(200).json({ token });


});

In this example, the /login endpoint verifies the user credentials and returns a JWT token
upon successful authentication.

Step 3: Middleware to Protect Endpoints


Next, create middleware to verify JWT tokens for protected endpoints.

// Middleware to authenticate using JWT


const authenticateJWT = (req, res, next) => {
const token = req.headers.authorization && req.headers.authorization.split(' ')[1];

if (!token) {
return res.status(401).json({ message: 'Token required' });
}

try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded; // Attach decoded user info to the request object
next();
} catch (err) {
return res.status(401).json({ message: 'Invalid or expired token' });
}
};

This middleware checks for a JWT token in the Authorization header and verifies it. If
the token is valid, the user information is attached to the request object; otherwise, it
responds with an unauthorized message.

Step 4: Apply JWT Authentication to Protected Endpoints


Now, you can apply the JWT authentication middleware to specific endpoints to protect
them.
// In-memory student data
let students = [
{ id: 1, name: 'John Doe', age: 20 },
{ id: 2, name: 'Jane Smith', age: 22 },
];

// CREATE: Add a new student (requires authentication)


app.post('/students', authenticateJWT, (req, res) =>
{ const { name, age } = req.body;
const newStudent = {
id: students.length + 1, // Simple ID generation
name,
age,
};
students.push(newStudent);
res.status(201).json(newStudent);
});

// READ: Get all students (requires authentication)


app.get('/students', authenticateJWT, (req, res) => {
res.status(200).json(students);
});

// READ: Get a student by ID (requires authentication)


app.get('/students/:id', authenticateJWT, (req, res) =>
{ const { id } = req.params;
const student = students.find((s) => s.id === parseInt(id));

if (student) {
res.status(200).json(student);
} else {
res.status(404).json({ message: 'Student not found' });
}
});

// UPDATE: Update a student's information by ID (requires authentication)


app.put('/students/:id', authenticateJWT, (req, res) => {
const { id } = req.params;
const { name, age } = req.body;
const student = students.find((s) => s.id === parseInt(id));

if (student) {
student.name = name || student.name;
student.age = age or student.age;
res.status(200).json(student);
} else {
return res.status(404).json({ message: 'Student not found' });
}
});

// DELETE: Delete a student by ID (requires authentication)


app.delete('/students/:id', authenticateJWT, (req, res) =>
{ const { id } = req.params;
const studentIndex = students.findIndex((s) => s.id === parseInt(id));

if (studentIndex !== -1) {


const deletedStudent = students.splice(studentIndex, 1)[0];
res.status(200).json(deletedStudent);
} else {
res.status(404).json({ message: 'Student not found' });
}
});

app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}/`);
});
Step 5: Test the REST API with JWT Protection in Postman
To test the endpoints with JWT-based authentication, use Postman:

Login Endpoint:
Method: POST
URL: http://localhost:3000/login
Body: { "username": "admin", "password": "adminpass" }
Expected Response: JWT token in JSON format { "token": "..." }
Protected Endpoints:
Add an Authorization header with the format Bearer <token>, where <token> is the JWT
obtained from the /login endpoint.
Test the endpoints /students, /students/:id, /students, /students/:id, /students/:id with the
appropriate HTTP methods (GET, POST, PUT, DELETE).
Ensure that you use the JWT token for each request to the protected endpoints. If a valid
token is not provided, the server should respond with a 401 Unauthorized status.

Conclusion
This guide shows how to implement JWT-based authentication and authorization for an
Express.js web application with CRUD operations on student data. The use of
middleware to verify JWT tokens allows you to secure specific endpoints and ensure that
only authorized users can access them. Test your application with Postman or other
similar tools to validate the JWT-based security.
EXPERIMENT: 12

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

To create a React application for a student management system with registration, login,
contact, and about pages, you can follow a step-by-step approach to set up a basic React
project, implement routing, and create the required pages. Here's a complete guide to
achieve this.

Step 1: Set Up a React Project


First, set up a new React project using Create React App (CRA).
# Create a new React project
npx create-react-app student-management

# Change directory to the newly created project


cd student-management

Step 2: Install React Router for Navigation


To implement routing, you'll need React Router, which allows you to define navigation
and manage page transitions in a React application.
# Install React Router
npm install react-router-dom

Step 3: Set Up Routing in the App Component


Create a basic routing structure in the main App component to manage navigation
between pages.

Jsx
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Navbar from './components/Navbar';
import Home from './pages/Home';
import Registration from './pages/Registration';
import Login from './pages/Login';
import Contact from './pages/Contact';
import About from './pages/About';
function App()
{ return (
<Router>
<div className="App">
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/register" component={Registration} />
<Route path="/login" component={Login} />
<Route path="/contact" component={Contact} />
<Route path="/about" component={About} />
</Switch>
</div>
</Router>
);
}

export default App;


In this example, a Navbar component is used for navigation, and various routes are
defined to handle different paths (/, /register, /login, /contact, and /about).

Step 4: Create the Navigation Bar


Create a simple navigation bar to allow users to navigate between different pages.

jsx
Copy code
// src/components/Navbar.js
import React from 'react';
import { Link } from 'react-router-dom';

function Navbar() {
return (
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/register">Registration</Link></li>
<li><Link to="/login">Login</Link></li>
<li><Link to="/contact">Contact</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
);
}

export default Navbar;


This navigation bar allows users to navigate between pages using Link components from
React Router.

Step 5: Create Page Components


Now, create the components for each of the pages: Home, Registration, Login, Contact,
and About.

Home Page
jsx
Copy code
// src/pages/Home.js
import React from 'react';

function Home()
{ return (
<div>
<h1>Welcome to the Student Management System</h1>
<p>Navigate through the registration, login, contact, or about pages using the
navigation bar.</p>
</div>
);
}

export default Home;


Registration Page
jsx
Copy code
// src/pages/Registration.js
import React, { useState } from 'react';

function Registration() {
const [formData, setFormData] = useState({
username: '',
password: '',
email: '',
});

const handleChange = (e) =>


{ const { name, value } =
e.target;
setFormData({ ...formData, [name]: value });
};

const handleSubmit = (e) => {


e.preventDefault();
console.log('Registration data:', formData);
// In a real application, you'd send this data to a server for processing
};

return (
<div>
<h1>Register</h1>
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input type="text" name="username" value={formData.username}
onChange={handleChange} />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" value={formData.password}
onChange={handleChange} />
</div>
<div>
<label>Email:</label>
<input type="email" name="email" value={formData.email}
onChange={handleChange} />
</div>
<button type="submit">Register</button>
</form>
</div>
);
}

export default Registration;


Login Page
jsx
Copy code
// src/pages/Login.js
import React, { useState } from 'react';

function Login() {
const [formData, setFormData] = useState({
username: '',
password: '',
});

const handleChange = (e) =>


{ const { name, value } =
e.target;
setFormData({ ...formData, [name]: value });
};

const handleSubmit = (e) => {


e.preventDefault();
console.log('Login data:', formData);
// In a real application, you'd authenticate the user with a server
};

return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input type="text" name="username" value={formData.username}
onChange={handleChange} />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" value={formData.password}
onChange={handleChange} />
</div>
<button type="submit">Login</button>
</form>
</div>
);
}

export default Login;


Contact Page
jsx
Copy code
// src/pages/Contact.js
import React from 'react';

function Contact() {
return (
<div>
<h1>Contact Us</h1>
<p>Email: [email protected]</p>
<p>Phone: 123-456-7890</p>
</div>
);
}

export default Contact;


About Page
jsx
Copy code
// src/pages/About.js
import React from 'react';

function About()
{ return (
<div>
<h1>About the Student Management System</h1>
<p>This system is designed to manage student information and facilitate registration,
login, and other functionalities.</p>
</div>
);
}

export default About;


Conclusion
This guide provides a basic React application with a navigation bar and routing to create
a student management system with registration, login, contact, and about pages. Each
page has a simple structure, and routing is implemented using React Router. To run the
application, use the following command:

bash
Copy code
npm start
This command starts the development server, allowing you to navigate through the
application and test the routing functionality. To enhance this application, consider
adding state management, user authentication, and interactions with a backend server for
storing and retrieving data.
EXPERIMENT: 13
3. 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

To create a React service that fetches weather information from OpenWeatherMap and
displays current and historical weather data using Chart.js, you need to follow these
steps:

Set Up a React Project


Install Required Dependencies
Create a Weather Service to Fetch Data
Display Weather Information
Visualize Weather Data with Chart.js
I'll walk you through each step in detail, including setting up the React project, creating a
service to fetch weather information from OpenWeatherMap, and using Chart.js to
represent data graphically.

Step 1: Set Up a React Project


First, create a new React project using Create React App.

bash
Copy code
npx create-react-app weather-app
cd weather-app
Step 2: Install Required Dependencies
Install the packages needed for interacting with OpenWeatherMap and creating charts
with Chart.js.

bash
Copy code
# Install Axios for making HTTP requests
npm install axios

# Install Chart.js and React-Chartjs-2 for graphical representation


npm install chart.js react-chartjs-2
Step 3: Create a Weather Service to Fetch Data
OpenWeatherMap provides weather data via an API. You need to sign up for an API key
and use it to fetch weather data.
Create a service to fetch weather data:

jsx
Copy code
// src/services/weatherService.js
import axios from 'axios';

const API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY'; // Replace with your


API key
const BASE_URL = 'https://api.openweathermap.org/data/2.5';

const getWeather = (city) => {


return axios.get(`${BASE_URL}/weather`,
{ params: {
q: city,
appid: API_KEY,
units: 'metric', // Use metric system for temperatures in Celsius
},
});
};

const getHistoricalWeather = (lat, lon) => {


const currentTimestamp = Math.floor(Date.now() / 1000);
const oneDaySeconds = 86400;

return axios.get(`${BASE_URL}/timemachine`,
{ params: {
lat,
lon,
dt: currentTimestamp - (7 * oneDaySeconds), // One week ago
appid: API_KEY,
units: 'metric',
},
});
};

export { getWeather, getHistoricalWeather };


This service provides two functions:
getWeather: Fetches the current weather for a given city.
getHistoricalWeather: Fetches historical weather data for a given latitude and longitude.
Step 4: Display Weather Information
Create a React component that fetches and displays the current weather for a specified
city.

jsx
Copy code
// src/components/WeatherDisplay.js
import React, { useEffect, useState } from 'react';
import { getWeather } from
'../services/weatherService';

function WeatherDisplay({ city }) {


const [weather, setWeather] = useState(null);

useEffect(() => {
const fetchWeather = async () =>
{ try {
const response = await getWeather(city);
setWeather(response.data);
} catch (error) {
console.error('Error fetching weather data:', error);
}
};

fetchWeather();
}, [city]);

if (!weather) {
return <div>Loading...</div>;
}

const { main, weather: weatherDetails, name } = weather;

return (
<div>
<h2>Weather in {name}</h2>
<p>Temperature: {main.temp} °C</p>
<p>Weather: {weatherDetails[0].description}</p>
</div>
);
}

export default WeatherDisplay;


This component fetches the current weather for a specified city and displays it.

Step 5: Visualize Weather Data with Chart.js


Create a React component that fetches historical weather data and displays it using
Chart.js.

jsx
Copy code
// src/components/WeatherChart.js
import React, { useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import { getWeather, getHistoricalWeather } from '../services/weatherService';

function WeatherChart({ city }) {


const [chartData, setChartData] = useState(null);

useEffect(() => {
const fetchHistoricalWeather = async () =>
{ try {
const currentWeather = await getWeather(city);
const { coord } = currentWeather.data;

const historicalWeather = await getHistoricalWeather(coord.lat, coord.lon);

const temperatureData = historicalWeather.data.hourly.map((hour) => ({


x: new Date(hour.dt * 1000),
y: hour.temp,
}));

setChartData({
datasets: [
{
label: 'Temperature over Time',
data: temperatureData,
borderColor: 'rgba(75, 192, 192,
1)',
borderWidth: 2,
fill: false,
},
],
});
} catch (error) {
console.error('Error fetching historical weather:', error);
}
};

fetchHistoricalWeather();
}, [city]);

if (!chartData) {
return <div>Loading...</div>;
}

return (
<div>
<h2>Temperature Chart for {city}</h2>
<Line data={chartData} />
</div>
);
}

export default WeatherChart;


This component fetches historical weather data for the specified city and displays it using
a line chart from Chart.js.

Step 6: Integrate Components in the App


Now, integrate the WeatherDisplay and WeatherChart components into the main App
component.

jsx
Copy code
// src/App.js
import React from 'react';
import WeatherDisplay from './components/WeatherDisplay';
import WeatherChart from './components/WeatherChart';

function App() {
const city = 'New York'; // Example city name

return (
<div className="App">
<h1>Weather Information</h1>
<WeatherDisplay city={city} />
<WeatherChart city={city} />
</div>
);
}

export default App;


This App component demonstrates how to use both components to display current
weather information and a temperature chart.

Conclusion
With this guide, you have created a React service to fetch weather information from
OpenWeatherMap and display it using Chart.js for graphical representation. The
WeatherDisplay component fetches and displays current weather, while the
WeatherChart component visualizes historical weather data. You can extend this
application with additional features like user input for city names, caching data to reduce
API calls, or more complex graphical representations. Remember to replace
'YOUR_OPENWEATHERMAP_API_KEY' with your actual OpenWeatherMap API
key.
EXPERIMENT: 14

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

Creating a TODO application in React involves several key steps: setting up the React
project, creating necessary components for the TODO functionality, adding CRUD
(Create, Read, Update, Delete) operations, and deploying the application to GitHub
Pages. This guide will walk you through each step, from project setup to deployment.

Step 1: Set Up the React Project


Start by creating a new React project using Create React App.

bas
h
npx create-react-app todo-app
cd todo-appapp

Step 2: Create TODO Components


Create components to manage the TODO list, including adding new tasks, listing
existing tasks, updating tasks, and deleting them. Here's a basic structure for the
components.

Task Component

A component that represents a single TODO item with the ability to


mark it as complete or delete it.

// src/components/Task.js
import React from 'react';

function Task({ task, onToggle, onDelete }) {


return (
<div>
<input
type="checkbox"
checked={task.completed}
onChange={() => onToggle(task.id)}
/>
<span style={{ textDecoration: task.completed ? 'line-through' : 'none' }}>
{task.text}
</span>
<button onClick={() => onDelete(task.id)}>Delete</button>
</div>
);
}

export default Task;


Task List Component
A component that displays a list of TODO items and allows for toggling
completion and deletion.

js
x
Copy
code
// // src/components/TaskList.js

import React from 'react';


import Task from './Task';

function TaskList({ tasks, onToggle, onDelete }) {


return (
<div className="task-list">
{tasks.map((task) => (
<Task
key={task.id}
task={task}
onToggle={onToggle}
onDelete={onDelete}
/>
))}
</div>
);
}

export default TaskList;


Add Task Component

A component that provides a form to add a new task to the TODO list.

// src/components/AddTask.js

import React, { useState } from 'react';

function AddTask({ onAdd }) {


const [taskText, setTaskText] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
if (taskText.trim() === '') {
return;
}
onAdd(taskText);
setTaskText('');
};

return (
<form onSubmit={handleSubmit} style={styles.form}>
<input
type="text"
placeholder="Enter a new task"
value={taskText}
onChange={(e) => setTaskText(e.target.value)}
style={styles.input}
/>
<button type="submit" style={styles.button}>
Add Task
</button>
</form>
);
}

const styles = {
form: {
display: 'flex',
gap: '10px',
marginBottom: '20px',
},
input: {
flexGrow: 1,
padding: '8px',
fontSize: '16px',
},
button: {
padding: '8px 16px',
fontSize: '16px',
backgroundColor: '#3498db',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
},
};

export default AddTask;

Step 3: Create the App Component


Now, create the App component to manage the overall state of the
TODO list, handle task additions, toggles, and deletions.
js
x

// src/App.js

import React, { useState } from 'react';


import TaskList from './components/TaskList';
import AddTask from './components/AddTask';

function App() {
const [tasks, setTasks] = useState([]);

const addTask = (text) => {


const newTask = {
id: tasks.length + 1,
text,
completed: false,
};
setTasks([...tasks, newTask]);
};

const toggleTask = (id) => {


setTasks(
tasks.map((task) =>
task.id === id ? { ...task, completed: !task.completed } : task
)
);
};

const deleteTask = (id) => {


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

return (
<div className="App" style={styles.container}>
<h1 style={styles.heading}>TODO Application</h1>
<AddTask onAdd={addTask} />
<TaskList tasks={tasks} onToggle={toggleTask} onDelete={deleteTask} />
</div>
);
}

const styles = {
container: {
maxWidth: '600px',
margin: '40px auto',
padding: '20px',
borderRadius: '8px',
backgroundColor: '#f8f9fa',
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
},
heading: {
textAlign: 'center',
color: '#2c3e50',
marginBottom: '20px',
},
};

export default App;


This App component provides a simple TODO list application with task creation,
completion toggling, and deletion functionality.

Step 4: Deploy the Application to GitHub Pages

To deploy your application to GitHub Pages, you need to set up the necessary
configurations.
Install gh-pages Package

Install the gh-pages package to manage the deployment process.

bas
h

npm install gh-pages --save-dev

Configure package.json

Update package.json to set up the deployment script and specify the GitHub repository for
deployment.

json

{
"name": "todo-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
},
"homepage": "https://<your-github-username>.github.io/todo-app"
}
Replace <your-github-username> with your actual GitHub username.

Push the Project to GitHub

Create a new GitHub repository, initialize your local Git repository, and push the project
to GitHub.
bas
h

# Initialize Git repository


git init
# Add and commit files
git add .
git commit -m "Initial commit for TODO app"
# Add GitHub remote repository
git remote add origin https://github.com/<your-github-username>/todo-app.git
# Push to GitHub
git push -u origin main

Replace <your-github-username> with your GitHub username.

Deploy to GitHub Pages

Finally, deploy the application to GitHub Pages.


bas
h

npm run deploy


This command will build the application and deploy it to GitHub Pages. You can then
visit the URL specified in package.json to see your deployed TODO application.

Conclusion
Following this guide, you have created a simple TODO application in React with task
creation, completion, and deletion functionality. You also deployed the application to
GitHub Pages, allowing you to share it with others or use it as a live demonstration. This
is a foundational project that you can expand with additional features like persistence,
user authentication, or more complex task management.

You might also like