Experiment 11 To 14
Experiment 11 To 14
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.
// 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
},
];
if (!user) {
return res.status(401).json({ message: 'Invalid username or password' });
}
if (!passwordValid) {
return res.status(401).json({ message: 'Invalid username or password' });
}
In this example, the /login endpoint verifies the user credentials and returns a JWT token
upon successful authentication.
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.
if (student) {
res.status(200).json(student);
} else {
res.status(404).json({ message: 'Student not found' });
}
});
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' });
}
});
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.
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>
);
}
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>
);
}
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>
);
}
function Registration() {
const [formData, setFormData] = useState({
username: '',
password: '',
email: '',
});
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>
);
}
function Login() {
const [formData, setFormData] = useState({
username: '',
password: '',
});
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>
);
}
function Contact() {
return (
<div>
<h1>Contact Us</h1>
<p>Email: [email protected]</p>
<p>Phone: 123-456-7890</p>
</div>
);
}
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>
);
}
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:
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
jsx
Copy code
// src/services/weatherService.js
import axios from 'axios';
return axios.get(`${BASE_URL}/timemachine`,
{ params: {
lat,
lon,
dt: currentTimestamp - (7 * oneDaySeconds), // One week ago
appid: API_KEY,
units: 'metric',
},
});
};
jsx
Copy code
// src/components/WeatherDisplay.js
import React, { useEffect, useState } from 'react';
import { getWeather } from
'../services/weatherService';
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>;
}
return (
<div>
<h2>Weather in {name}</h2>
<p>Temperature: {main.temp} °C</p>
<p>Weather: {weatherDetails[0].description}</p>
</div>
);
}
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';
useEffect(() => {
const fetchHistoricalWeather = async () =>
{ try {
const currentWeather = await getWeather(city);
const { coord } = currentWeather.data;
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>
);
}
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>
);
}
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.
bas
h
npx create-react-app todo-app
cd todo-appapp
Task Component
// src/components/Task.js
import React from 'react';
js
x
Copy
code
// // src/components/TaskList.js
A component that provides a form to add a new task to the TODO list.
// src/components/AddTask.js
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',
},
};
// src/App.js
function App() {
const [tasks, setTasks] = useState([]);
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',
},
};
To deploy your application to GitHub Pages, you need to set up the necessary
configurations.
Install gh-pages Package
bas
h
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.
Create a new GitHub repository, initialize your local Git repository, and push the project
to GitHub.
bas
h
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.