0% found this document useful (0 votes)
32 views23 pages

Webd File

Uploaded by

warril abhishek
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)
32 views23 pages

Webd File

Uploaded by

warril abhishek
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/ 23

Practical 1

Using various HTML tags for creating different web pages.


Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Tags Example</title>
</head>
<body>
<h1>Welcome to Web Development II</h1>
<p>This is a sample page to demonstrate various HTML tags.</p>
<p><strong>Bold Text</strong></p>
<p><em>Italic Text</em></p>
<p><u>Underlined Text</u></p>
<p><mark>Highlighted Text</mark></p>
<h2>Types of Lists</h2>
<ul>
<li>Unordered List Item 1</li>
<li>Unordered List Item 2</li>
</ul>
<ol>
<li>Ordered List Item 1</li>
<li>Ordered List Item 2</li> </ol>
<h2>Student Information</h2>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Course</th>
</tr>
<tr>
<td>John Doe</td>
<td>20</td>
<td>Web Development</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>22</td>
<td>Database Systems</td>
</tr>
</table>
<h2>Registration Form</h2>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br> <label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Register"> </form>
<h2>Links and Images</h2>
<p><a href="https://www.example.com">Visit Example.com</a></p>
<img src="https://www.example.com/image.jpg" alt="Example Image" width="200">
<h2>Multimedia</h2>
<h3>Audio</h3>
<audio controls>
<source src="audio-file.mp3" type="audio/mpeg"> Your browser
does not support the audio element. </audio>
<h3>Video</h3>
<video width="320" height="240" controls> <source
src="video-file.mp4" type="video/mp4"> Your browser does
not support the video tag. </video>
<header>
<h1>Website Header</h1>
<p>This is the main header of the website.</p> </header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul> </nav>
<main>
<section>
<h2>Main Content Section</h2>
<p>This is the main content of the page.</p>
</section> </main>
<footer>
<p>&copy; 2024 My Website</p> </footer>
</body>
</html>
Output :
Practical 2
Using various Form tags for interactivity, authentication, date validation etc.
Code : <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Tags Example</title>
</head>
<body>
<h1>Form Examples for Interactivity, Authentication, and Validation</h1>
<!-- Text Input for Name -->
<h2>Basic Information</h2>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<!-- Email Input for Authentication -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<!-- Password Input for Authentication -->
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<!-- Phone Number with Pattern Validation -->
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}"
placeholder="1234567890"><br><br>
<!-- Number Input with Range -->
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="99" required><br><br>
<!-- Date Input for Date of Birth Validation -->
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" max="2006-12-31" required><br><br>
<!-- Color Picker -->
<label for="color">Favorite Color:</label>
<input type="color" id="color" name="color"><br><br>
<!-- Radio Buttons for Gender Selection -->
<label>Gender:</label><br>
<input type="radio" id="male" name="gender" value="Male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br><br>
<!-- Dropdown for Country Selection -->
<label for="country">Country:</label>
<select id="country" name="country">
<option value="India">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Canada">Canada</option>
</select><br><br>
<!-- Checkbox for Terms and Conditions -->
<input type="checkbox" id="terms" name="terms" required>
<label for="terms">I agree to the terms and conditions</label><br><br>
<!-- Range Slider for Satisfaction Rating -->
<label for="satisfaction">Satisfaction (1-10):</label>
<input type="range" id="satisfaction" name="satisfaction" min="1" max="10" value="5"><br><br>
<!-- File Upload for Profile Picture -->
<label for="profilePic">Upload Profile Picture:</label>
<input type="file" id="profilePic" name="profilePic" accept="image/*"><br><br>
<!-- Date and Time for Event Selection -->
<label for="event">Event Date and Time:</label>
<input type="datetime-local" id="event" name="event"><br><br>
<!-- Submit Button -->
<input type="submit" value="Submit">
</form>
</body> </html>
Output :
Practical 3
Using Semantic HTML tags /tags associated with interactivity.
Code : <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Semantic HTML and Interactivity</title>
</head>
<body>
<!-- Header: Using semantic header tag for main navigation and logo -->
<header>
<h1>My Web Development Page</h1>
<nav>
<ul>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<!-- Main content with sections and interactivity elements -->
<main>
<!-- About Section -->
<section id="about">
<h2>About Us</h2>
<p>We specialize in creating interactive and responsive web applications using modern
technologies.</p> </section>
<!-- Services Section with Interactivity Elements -->
<section id="services">
<h2>Our Services</h2>
<!-- Article tag to represent individual service information -->
<article>
<h3>Web Development</h3>
<p>We offer full-stack web development services.</p>
<button onclick="alert('Learn more about Web Development')">Learn More</button>
</article>
<article>
<h3>SEO Optimization</h3>
<p>Improve your website's visibility in search engines with our SEO services.</p>
<button onclick="alert('Learn more about SEO Optimization')">Learn More</button>
</article>
</section>
<!-- Form Section for Contacting Us -->
<section id="contact">
<h2>Contact Us</h2>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" required></textarea><br><br>
<input type="submit" value="Send Message">
</form>
</section>
</main>
<!-- Aside: Additional interactive content related to main content -->
<aside>
<h3>Upcoming Events</h3>
<p>Don't miss our upcoming webinar on web accessibility!</p>
<button onclick="alert('Sign up for the webinar')">Sign Up</button>
</aside>
<!-- Footer with social media links -->
<footer>
<p>&copy; 2024 My Web Development Page</p>
<ul>
<li><a href="https://www.facebook.com">Facebook</a></li>
<li><a href="https://www.twitter.com">Twitter</a></li>
<li><a href="https://www.linkedin.com">LinkedIn</a></li>
</ul>
</footer>
</body> </html>
Output :
Practical 4 :
Using DHTML tags in concern to client server application
Code : <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DHTML Example - Client-Server Interaction</title>
<style> #response {
margin-top: 20px; padding:
10px; border: 1px solid #ccc;
background-color: #f9f9f9;
}
.loading { font-
weight: bold; color: blue;
}
</style>
</head>
<body>
<h1>Interactive Content with DHTML</h1>
<button onclick="fetchData()">Get Server Data</button>
<div id="response">Server response will appear here.</div>
<script>
function fetchData() {
const responseDiv = document.getElementById('response'); responseDiv.innerHTML = '<p
class="loading">Loading data...</p>';
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status ===
200) { const data = JSON.parse(xhr.responseText);
responseDiv.innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;
} };
xhr.send();
}
</script>
</body>
</html>
Output :
Practical 5
Using JavaScript/CSS for dynamic web pages.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Web Page with JavaScript and CSS</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f4f8;
display: flex; flex-direction:
column; align-items: center;
margin: 0;
} h1 {
color: #333;
margin-top: 20px;
}
#dynamicBox { width:
200px; height: 200px;
background-color: #3498db;
display: flex;
align-items: center;
justify-content: center;
color: white; font-size:
20px; font-weight:
bold; margin-top:
20px;
transition: transform 0.3s, background-color 0.3s;
}
#changeColorButton, #toggleTextButton {
padding: 10px 20px; font-size: 16px;
margin: 10px; cursor: pointer;
border: none; border-radius: 5px;
background-color: #3498db; color:
white;
transition: background-color 0.3s;
}
#changeColorButton:hover, #toggleTextButton:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<h1>Interactive Box with JavaScript and CSS</h1>
<div id="dynamicBox">Hover Me!</div>
<button id="changeColorButton">Change Color</button>
<button id="toggleTextButton">Toggle Text</button>
<script>
const dynamicBox = document.getElementById('dynamicBox'); const
changeColorButton = document.getElementById('changeColorButton'); const
toggleTextButton = document.getElementById('toggleTextButton');
dynamicBox.addEventListener('mouseover', function() {
dynamicBox.style.transform = 'scale(1.1)';
});
dynamicBox.addEventListener('mouseout', function() {
dynamicBox.style.transform = 'scale(1)';
});
changeColorButton.addEventListener('click', function() {
const colors = ['#e74c3c', '#9b59b6', '#f1c40f', '#1abc9c'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
dynamicBox.style.backgroundColor = randomColor;
});
toggleTextButton.addEventListener('click', function() {
dynamicBox.textContent = dynamicBox.textContent === 'Hover Me!' ? 'Hello World!' : 'Hover Me!';
});
</script>
</body>
</html>
Output :
Practical 6
Utilize HTML/CSS and JavaScript frameworks (ReactJS, NextJS) to construct dynamic user interfaces.
Code : App.js
import React, { useState } from "react"; import
"./App.css";
function App() {
const [count, setCount] = useState(0); const [darkMode,
setDarkMode] = useState(false);
const incrementCount = () => setCount(count + 1); const
toggleTheme = () => setDarkMode(!darkMode);
return (
<div className={`App ${darkMode ? "dark" : "light"}`}>
<header className="App-header">
<h1>Dynamic User Interface</h1>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment Count</button>
<button onClick={toggleTheme}>
Switch to {darkMode ? "Light" : "Dark"} Mode
</button>
</header>
</div>
);
} export default App;

App.css
.App {
text-align: center; }
.App-logo { height:
40vmin; pointer-events:
none; }
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34; min-
height: 100vh; display: flex; flex-
direction: column; align-items:
center; justify-content: center; font-
size: calc(10px + 2vmin); color:
white;
}
.App-link { color:
#61dafb; }
@keyframes App-logo-spin { from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}}
Output :
Practical 7
Create various databases using SQL/MongoDB/or other to show interactivity.
CREATE DATABASE interactiveDB;
USE interactiveDB;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL, email
VARCHAR(100) NOT NULL, password
VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO users (username, email, password) VALUES


('alice', '[email protected]', 'alice123'),
('bob', '[email protected]', 'bob123'); SELECT *
FROM users;

const mysql = require('mysql2'); const connection


= mysql.createConnection({
host: 'localhost', user:
'yourUsername', password:
'yourPassword', database:
'interactiveDB'
});
connection.connect((err) => {
if (err) throw err;
console.log("Connected to MySQL database.");
});
function addUser(username, email, password) {
const query = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';
connection.query(query, [username, email, password], (err, results) => { if
(err) throw err;
console.log("User added:", results);
}); }
addUser('david', '[email protected]', 'david123');
Practical 8
Perform CRUD operations using React JS as frontend technology and Node JS as backend
technology.
Code Frontend
App.js
import React, { useEffect, useState } from "react"; import api
from "./api";
function App() {
const [users, setUsers] = useState([]);
const [formData, setFormData] = useState({ name: "", email: "", age: "" });
const fetchUsers = async () => { const
response = await api.get("/users");
setUsers(response.data);
};
useEffect(() => { fetchUsers();
}, []);
const handleSubmit = async (e) => {
e.preventDefault(); if (formData._id) {
await api.put(`/users/${formData._id}`, formData);
} else {
await api.post("/users", formData);
}
setFormData({ name: "", email: "", age: "" }); fetchUsers();
};
const handleEdit = (user) => { setFormData(user);
};
const handleDelete = async (id) => { await
api.delete(`/users/${id}`); fetchUsers();
};
return (
<div>
<h1>CRUD Application</h1>
<form onSubmit={handleSubmit}>
<input type="text"
placeholder="Name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>
<input type="email"
placeholder="Email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
/>
<input
type="number"
placeholder="Age"
value={formData.age}
onChange={(e) => setFormData({ ...formData, age: e.target.value })}
/>
<button type="submit">Submit</button>
</form>
<ul>
{users.map((user) => (
<li key={user._id}>
{user.name} - {user.email} - {user.age} years
<button onClick={() => handleEdit(user)}>Edit</button>
<button onClick={() => handleDelete(user._id)}>Delete</button>
</li>
))}
</ul>
</div>
);
} export default App;
api.js import axios from
'axios';
export default axios.create({ baseURL:
'http://localhost:5001' });
Backend
// index.js
const express = require("express"); const
mongoose = require("mongoose"); const
cors = require("cors"); const app =
express(); const PORT = 5001;
app.use(cors()); app.use(express.json());
mongoose
.connect("mongodb://localhost:27017/crudDB")
.then(() => console.log("Connected to MongoDB")) .catch((err) =>
console.log("Database connection error:", err));
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
const User = require("./models/User");
// CREATE
app.post("/users", async (req, res) => { try {
const user = new User(req.body); await
user.save(); res.status(201).json(user);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// READ
app.get("/users", async (req, res) => {
try {
const users = await User.find();
res.json(users); }
catch (error) {
res.status(500).json({ message: error.message });
}
});
// UPDATE
app.put("/users/:id", async (req, res) => { try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, {
new: true, }); res.json(user); } catch (error) {
res.status(400).json({ message: error.message });
}
});
// DELETE
app.delete("/users/:id", async (req, res) => { try {
await User.findByIdAndDelete(req.params.id); res.json({
message: "User deleted" });
} catch (error) {
res.status(500).json({ message: error.message });
}
});
User.js const mongoose =

require("mongoose");

const UserSchema = new mongoose.Schema({


name: String,
email: String, age:
Number,
});
module.exports = mongoose.model("User", UserSchema);
Output
Practical 9
Develop robust back-end systems using Node.js.
Code
Index.js
const express = require('express'); const connectDB
= require('./db'); const authRoutes =
require('./routes/auth'); const protectedRoutes =
require('./routes/protected'); const cors =
require('cors'); const app = express();
// Connect to MongoDB connectDB();
app.use(cors()); app.use(express.json());
// Routes
app.use('/api/auth', authRoutes); app.use('/api',
protectedRoutes);
const PORT = process.env.PORT || 5000; app.listen(PORT,
() => {
console.log(`Server running on http://localhost:${PORT}`); });
DB.js
const mongoose = require("mongoose"); require("dotenv").config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connected.");
} catch (error) {
console.error("MongoDB connection error:", error);
process.exit(1);
}
};
module.exports = connectDB;
models/User.js
const mongoose = require("mongoose"); const
bcrypt = require("bcryptjs");
const UserSchema = new mongoose.Schema({
name: { type: String, required: true }, email: {
type: String, required: true, unique: true },
password: { type: String, required: true }, });
UserSchema.pre("save", async function (next) { if
(!this.isModified("password")) return next(); const salt
= await bcrypt.genSalt(10); this.password = await
bcrypt.hash(this.password, salt); next();
});
module.exports = mongoose.model("User", UserSchema);
// routes/auth.js const express =
require("express"); const User =
require("../models/User"); const jwt =
require("jsonwebtoken"); const bcrypt
= require("bcryptjs");
require("dotenv").config(); const router
= express.Router();
// Register User
router.post("/register", async (req, res) => {
const { name, email, password } = req.body;
try {
const user = new User({ name, email, password });
await user.save();
res.status(201).json({ message: "User registered successfully" });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Login User
router.post("/login", async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email }); if (!user) return
res.status(400).json({ message: "User not found" });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: "Invalid
credentials" });
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
res.json({ token });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
.env
PORT=5001
MONGO_URI=mongodb://localhost:27017/backendDB
JWT_SECRET=aerondhruvaerondhruvaerondhruvaerondhruv
// middleware/auth.js const jwt =
require("jsonwebtoken");
require("dotenv").config();
const auth = (req, res, next) => { const
token = req.header("x-auth-token"); if
(!token)
return res.status(401).json({ message: "No token, authorization denied" });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded; next(); } catch (error) {
res.status(401).json({ message: "Token is not valid" });
}
};
module.exports = auth;
// routes/protected.js const express =
require("express"); const auth =
require("../middleware/auth"); const router
= express.Router();
router.get("/dashboard", auth, (req, res) => {
res.json({ message: `Welcome to your dashboard, user ID: ${req.user.id}` });
});
module.exports = router;
Output
Practical 10
Showing database interactivity using PHP/Python/or any current technology used in web
industry.
Code Frontend
App.js
import React, { useEffect, useState } from "react"; import
api from "./api";
function App() {
const [users, setUsers] = useState([]);
const [formData, setFormData] = useState({ name: "", email: "", age: "" });
const fetchUsers = async () => { const
response = await api.get("/users");
setUsers(response.data);
};
useEffect(() => {
fetchUsers();
}, []);
const handleSubmit = async (e) => {
e.preventDefault(); if
(formData._id) {
await api.put(`/users/${formData._id}`, formData);
} else {
await api.post("/users", formData);
}
setFormData({ name: "", email: "", age: "" });
fetchUsers();
};
const handleEdit = (user) => {
setFormData(user);
};
const handleDelete = async (id) => {
await api.delete(`/users/${id}`);
fetchUsers();
};
return (
<div>
<h1>CRUD Application</h1>
<form onSubmit={handleSubmit}>
<input type="text"
placeholder="Name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>
<input
type="email"
placeholder="Email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
/>
<input
type="number"
placeholder="Age"
value={formData.age}
onChange={(e) => setFormData({ ...formData, age: e.target.value })}
/>
<button type="submit">Submit</button>
</form>
<ul>
{users.map((user) => (
<li key={user._id}>
{user.name} - {user.email} - {user.age} years
<button onClick={() => handleEdit(user)}>Edit</button>
<button onClick={() => handleDelete(user._id)}>Delete</button>
</li>
))}
</ul>
</div>
);
} export default

App;

api.js import axios from


'axios';
export default axios.create({
baseURL: 'http://localhost:5001' });
Backend
// index.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors"); const app
= express(); const PORT = 5001;
app.use(cors()); app.use(express.json());
mongoose
.connect("mongodb://localhost:27017/crudDB")
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.log("Database connection error:", err));
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
const User = require("./models/User");
// CREATE
app.post("/users", async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user); } catch
(error) {
res.status(400).json({ message: error.message });
}
});
// READ
app.get("/users", async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// UPDATE
app.put("/users/:id", async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, {
new: true, }); res.json(user); } catch (error) {
res.status(400).json({ message: error.message });
}
});
// DELETE
app.delete("/users/:id", async (req, res) => {
try {
await User.findByIdAndDelete(req.params.id);
res.json({ message: "User deleted" });
} catch (error) {
res.status(500).json({ message: error.message });
}
});
User.js const mongoose =

require("mongoose");

const UserSchema = new mongoose.Schema({


name: String,
email: String, age:
Number,
});
module.exports = mongoose.model("User", UserSchema);
Output
Practical 11
Any current web industry relevant example of database usage and interactivity using
any suitable backend technology.
Code
Index.js
const express = require('express'); const connectDB = require('./db'); const authRoutes = require('./routes/auth'); const
protectedRoutes = require('./routes/protected'); const cors = require('cors'); const app = express();
// Connect to MongoDB connectDB();
app.use(cors()); app.use(express.json());
// Routes
app.use('/api/auth', authRoutes); app.use('/api', protectedRoutes);
const PORT = process.env.PORT || 5000; app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
DB.js
const mongoose = require("mongoose"); require("dotenv").config();
const connectDB = async () => { try {
await mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connected.");
} catch (error) {
console.error("MongoDB connection error:", error); process.exit(1);
}
};
module.exports = connectDB;
models/User.js
const mongoose = require("mongoose"); const bcrypt = require("bcryptjs");
const UserSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true,
unique: true }, password: { type: String, required: true }, });
UserSchema.pre("save", async function (next) { if (!this.isModified("password")) return next(); const salt = await
bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next();
});
module.exports = mongoose.model("User", UserSchema);
// routes/auth.js const express = require("express"); const User = require("../models/User"); const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs"); require("dotenv").config(); const router = express.Router();
// Register User
router.post("/register", async (req, res) => {
const { name, email, password } = req.body; try {
const user = new User({ name, email, password }); await user.save();
res.status(201).json({ message: "User registered successfully" });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Login User
router.post("/login", async (req, res) => {
const { email, password } = req.body; try {
const user = await User.findOne({ email }); if (!user) return res.status(400).json({ message: "User not found" });
const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ message:
"Invalid credentials" });
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h",
});
res.json({ token }); } catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
.env
PORT=5001
MONGO_URI=mongodb://localhost:27017/backendDB
JWT_SECRET=aerondhruvaerondhruvaerondhruvaerondhruv
// middleware/auth.js const jwt = require("jsonwebtoken"); require("dotenv").config();
const auth = (req, res, next) => { const token = req.header("x-auth-token"); if (!token)
return res.status(401).json({ message: "No token, authorization denied" });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch (error) {
res.status(401).json({ message: "Token is not valid" });
}
};
module.exports = auth;
// routes/protected.js const express = require("express"); const auth = require("../middleware/auth"); const router =
express.Router();
router.get("/dashboard", auth, (req, res) => {
res.json({ message: `Welcome to your dashboard, user ID: ${req.user.id}` });
});
module.exports = router;
Output
INDEX
S.NO. NAME OF PRACTICAL SIGN

1 Using various HTML tags for creating different web pages.

Using various Form tags for interactivity, authentication,


2 date validation etc

3 Using Semantic HTML tags /tags associated with interactivity.

4 Using DHTML tags in concern to client server application

5 Using JavaScript/CSS for dynamic web pages.

Utilize HTML/CSS and JavaScript frameworks (ReactJS,


6 NextJS) to construct dynamic user interfaces.

Create various databases using SQL/MongoDB/or other to


7
show interactivity.

Perform CRUD operations using React JS as frontend


8 technology and Node JS as backend
technology

9 Develop robust back-end systems using Node.js.

Showing database interactivity using


10 PHP/Python/or any current technology used in web industry.

Any current web industry relevant example of database usage


11 and interactivity using any suitable backend technology.

You might also like