Laboratory Experiments Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Book Details</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Book Details</h1>
<div class="book">
<h2>Title: JavaScript: The Good Parts</h2>
<p><strong>Author:</strong> Douglas Crockford</p>
<p><strong>Genre:</strong> Programming</p>
<p><strong>Published:</strong> 2008</p>
</div>
<div class="book">
<h2>Title: Eloquent JavaScript</h2>
<p><strong>Author:</strong> Marijn Haverbeke</p>
<p><strong>Genre:</strong> Programming</p>
<p><strong>Published:</strong> 2018</p>
</div>
</body>
</html>
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const server = http.createServer((req, res) => {
let filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url);
const extname = path.extname(filePath);
let contentType = 'text/html';
switch (extname) {
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
}
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code == 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>');
} else {
res.writeHead(500);
res.end(`Server Error: ${err.code}`);
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
}
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f0f8ff;
color: #333;
}
h1 {
text-align: center;
color: #0066cc;
}
.book {
background: #ffffff;
border: 1px solid #ccc;
padding: 15px;
margin: 20px auto;
width: 60%;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const app = express();
const PORT = 3000;
// Handlebars setup
app.engine('hbs', exphbs.engine({ extname: '.hbs', defaultLayout: 'main' }));
app.set('view engine', 'hbs');
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
// Routes
app.get('/', (req, res) => res.render('quiz'));
app.post('/submit', (req, res) => {
const { name, answer } = req.body;
const score = (answer === "Delhi") ? 1 : 0;
res.render('result', { name, answer, score });
});
// Start server
app.listen(PORT, () => console.log(`http://localhost:${PORT}`));
<!DOCTYPE html>
<html>
<head>
<title>Quiz</title>
</head>
<body>
{{{body}}}
</body>
</html>
<h1>Simple Quiz</h1>
<form action="/submit" method="POST">
<label>Name: </label>
<input type="text" name="name" required><br><br>
<p>What is the capital of India?</p>
<label><input type="radio" name="answer" value="Delhi" required> Delhi</label><br>
<label><input type="radio" name="answer" value="Mumbai"> Mumbai</label><br>
<label><input type="radio" name="answer" value="Kolkata"> Kolkata</label><br>
<label><input type="radio" name="answer" value="Chennai"> Chennai</label><br><br>
<button type="submit">Submit</button>
</form>
<h1>Result</h1>
<p>Name: {{name}}</p>
<p>Your Answer: {{answer}}</p>
<p>Score: {{score}} / 1</p>
<a href="/">Try Again</a>
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Student = require('./models/Student');
const app = express();
const PORT = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/studentDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Home Page - List all students
app.get('/', async (req, res) => {
const students = await Student.find();
res.render('studentList', { students });
});
// Add Student Form
app.get('/add', (req, res) => {
res.render('addStudent');
});
// Save Student to DB
app.post('/add', async (req, res) => {
const { name, roll, department, email } = req.body;
const student = new Student({ name, roll, department, email });
await student.save();
res.redirect('/');
});
// Edit Form
app.get('/edit/:id', async (req, res) => {
const student = await Student.findById(req.params.id);
res.render('editStudent', { student });
});
// Update student in DB
app.post('/edit/:id', async (req, res) => {
const { name, roll, department, email } = req.body;
await Student.findByIdAndUpdate(req.params.id, { name, roll, department, email });
res.redirect('/');
});
// Delete student
app.get('/delete/:id', async (req, res) => {
await Student.findByIdAndDelete(req.params.id);
res.redirect('/');
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({
name: String,
roll: String,
department: String,
email: String,
});
module.exports = mongoose.model('Student', studentSchema);
<h2>Add New Student</h2>
<form action="/add" method="POST">
<label>Name:</label><br>
<input type="text" name="name" required><br>
<label>Roll No:</label><br>
<input type="text" name="roll" required><br>
<label>Department:</label><br>
<input type="text" name="department" required><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<button type="submit">Add Student</button>
</form>
<a href="/">Back to Student List</a>
<h2>Edit Student</h2>
<form action="/edit/<%= student._id %>" method="POST">
<label>Name:</label><br>
<input type="text" name="name" value="<%= student.name %>" required><br>
<label>Roll No:</label><br>
<input type="text" name="roll" value="<%= student.roll %>" required><br>
<label>Department:</label><br>
<input type="text" name="department" value="<%= student.department %>" required><br>
<label>Email:</label><br>
<input type="email" name="email" value="<%= student.email %>" required><br><br>
<button type="submit">Update</button>
</form>
<a href="/">Back</a>
<h2>Student Details</h2>
<a href="/add">Add New Student</a>
<table border="1" cellpadding="8" cellspacing="0">
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Department</th>
<th>Email</th>
<th>Actions</th>
</tr>
<% students.forEach(student => { %>
<tr>
<td><%= student.name %></td>
<td><%= student.roll %></td>
<td><%= student.department %></td>
<td><%= student.email %></td>
<td>
<a href="/edit/<%= student._id %>">Edit</a> |
<a href="/delete/<%= student._id %>" onclick="return confirm('Delete this student?')">Delete</a>
</td>
</tr>
<% }) %>
</table>
const express = require("express");
const mysql = require("mysql2");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const port = 3000;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public")); // Serve HTML files from public folder
// MySQL Connection
const db = mysql.createConnection({
host: "localhost",
user: "root", // change if your MySQL user is different
password: "", // add your MySQL password if set
database: "eventdb"
});
db.connect(err => {
if (err) {
console.error("Database connection failed:", err);
return;
}
console.log("Connected to MySQL database");
});
// Serve index.html
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// CRUD Routes
// Create Event
app.post("/add-event", (req, res) => {
const { name, date, location, description } = req.body;
const sql = "INSERT INTO events (name, date, location, description) VALUES (?, ?, ?, ?)";
db.query(sql, [name, date, location, description], (err, result) => {
if (err) throw err;
res.send("Event added successfully! <a href='/'>Go Back</a>");
});
});
// Read Events
app.get("/events", (req, res) => {
db.query("SELECT * FROM events", (err, results) => {
if (err) throw err;
res.json(results);
});
});
// Update Event
app.post("/update-event", (req, res) => {
const { id, name, date, location, description } = req.body;
const sql = "UPDATE events SET name=?, date=?, location=?, description=? WHERE id=?";
db.query(sql, [name, date, location, description, id], (err, result) => {
if (err) throw err;
res.send("Event updated successfully! <a href='/'>Go Back</a>");
});
});
// Delete Event
app.post("/delete-event", (req, res) => {
const { id } = req.body;
const sql = "DELETE FROM events WHERE id=?";
db.query(sql, [id], (err, result) => {
if (err) throw err;
res.send("Event deleted successfully! <a href='/'>Go Back</a>");
});
});
// Start Server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Management</title>
</head>
<body>
<h1>Event Management System</h1>
<!-- Add Event -->
<h2>Add Event</h2>
<form action="/add-event" method="POST">
<input type="text" name="name" placeholder="Event Name" required><br>
<input type="date" name="date" required><br>
<input type="text" name="location" placeholder="Location" required><br>
<textarea name="description" placeholder="Description"></textarea><br>
<button type="submit">Add Event</button>
</form>
<hr>
<!-- Update Event -->
<h2>Update Event</h2>
<form action="/update-event" method="POST">
<input type="number" name="id" placeholder="Event ID" required><br>
<input type="text" name="name" placeholder="New Event Name" required><br>
<input type="date" name="date" required><br>
<input type="text" name="location" placeholder="New Location" required><br>
<textarea name="description" placeholder="New Description"></textarea><br>
<button type="submit">Update Event</button>
</form>
<hr>
<!-- Delete Event -->
<h2>Delete Event</h2>
<form action="/delete-event" method="POST">
<input type="number" name="id" placeholder="Event ID" required><br>
<button type="submit">Delete Event</button>
</form>
<hr>
<!-- View Events -->
<h2>View All Events</h2>
<button onclick="fetchEvents()">Show Events</button>
<pre id="eventList"></pre>
<script>
async function fetchEvents() {
const res = await fetch("/events");
const data = await res.json();
document.getElementById("eventList").textContent = JSON.stringify(data, null, 2);
}
</script>
</body>
</html>
import React from "react";
import Counter from "./Counter";
function App() {
return (
<div>
<Counter />
</div>
);
}
export default App;
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(0);
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>React Counter</h1>
<h2>{count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement} style={{ margin: "0 10px" }}>
Decrement
</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Counter;
const express = require("express");
const fs = require("fs");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
const PORT = 5000;
const DATA_FILE = "todos.json";
app.use(cors());
app.use(bodyParser.json());
const readTodos = () => JSON.parse(fs.readFileSync(DATA_FILE));
const writeTodos = (todos) => fs.writeFileSync(DATA_FILE, JSON.stringify(todos, null, 2));
app.get("/todos", (req, res) => res.json(readTodos()));
app.post("/todos", (req, res) => {
const todos = readTodos();
const newTodo = { id: Date.now(), text: req.body.text, completed: false };
todos.push(newTodo);
writeTodos(todos);
res.json(newTodo);
});
app.put("/todos/:id", (req, res) => {
const todos = readTodos().map((t) =>
t.id === parseInt(req.params.id) ? { ...t, completed: !t.completed } : t
);
writeTodos(todos);
res.json(todos);
});
app.delete("/todos/:id", (req, res) => {
const todos = readTodos().filter((t) => t.id !== parseInt(req.params.id));
writeTodos(todos);
res.json(todos);
});
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
import React, { useState, useEffect } from "react";
function App() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState("");
useEffect(() => {
fetch("http://localhost:5000/todos")
.then((res) => res.json())
.then((data) => setTodos(data));
}, []);
const addTodo = () => {
if (!newTodo.trim()) return;
fetch("http://localhost:5000/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: newTodo }),
})
.then((res) => res.json())
.then((todo) => setTodos([...todos, todo]));
setNewTodo("");
};
const toggleTodo = (id) => {
fetch(`http://localhost:5000/todos/${id}`, { method: "PUT" })
.then((res) => res.json())
.then((updated) => setTodos(updated));
};
const deleteTodo = (id) => {
fetch(`http://localhost:5000/todos/${id}`, { method: "DELETE" })
.then((res) => res.json())
.then((updated) => setTodos(updated));
};
return (
<div style={{ padding: "20px" }}>
<h1>Placement Preparation Todo App</h1>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Enter a task"
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo) => (
<li
key={todo.id}
style={{
textDecoration: todo.completed ? "line-through" : "none",
cursor: "pointer"
}}
>
<span onClick={() => toggleTodo(todo.id)}>{todo.text}</span>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default App;
[
{ "id": 1, "text": "Update resume and LinkedIn profile", "completed": false },
{ "id": 2, "text": "Practice aptitude questions", "completed": false },
{ "id": 3, "text": "Revise core CS subjects", "completed": false },
{ "id": 4, "text": "Solve coding problems on LeetCode", "completed": false },
{ "id": 5, "text": "Prepare for HR interview questions", "completed": false }
]
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const app = express();
const PORT = 5000;
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors({ origin: "http://localhost:3000", credentials: true }));
mongoose.connect("mongodb://127.0.0.1:27017/authDB")
.then(() => console.log("Connected to MongoDB"))
.catch(err => console.error(err));
const userSchema = new mongoose.Schema({ username: String, password: String });
const User = mongoose.model("User", userSchema);
app.post("/signup", async (req, res) => {
const { username, password } = req.body;
const existingUser = await User.findOne({ username });
if (existingUser) return res.status(400).json({ message: "User already exists" });
const newUser = new User({ username, password });
await newUser.save();
res.json({ message: "Signup successful" });
});
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username, password });
if (!user) return res.status(401).json({ message: "Invalid credentials" });
res.cookie("authUser", username, { httpOnly: true });
res.json({ message: "Login successful" });
});
app.get("/dashboard", (req, res) => {
if (!req.cookies.authUser) return res.status(401).json({ message: "Unauthorized access" });
res.json({ message: `Welcome ${req.cookies.authUser}, this is your dashboard!` });
});
app.post("/logout", (req, res) => {
res.clearCookie("authUser");
res.json({ message: "Logged out successfully" });
});
app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));
{
"name": "signup-login-cookies",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.0.3",
"body-parser": "^1.20.2",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5"
}
}
import React, { useState } from "react";
function App() {
const [signupUser, setSignupUser] = useState("");
const [signupPass, setSignupPass] = useState("");
const [loginUser, setLoginUser] = useState("");
const [loginPass, setLoginPass] = useState("");
const [dashboardMsg, setDashboardMsg] = useState("");
const handleSignup = async () => {
const res = await fetch("http://localhost:5000/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: signupUser, password: signupPass }),
credentials: "include"
});
const data = await res.json();
alert(data.message);
};
const handleLogin = async () => {
const res = await fetch("http://localhost:5000/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: loginUser, password: loginPass }),
credentials: "include"
});
const data = await res.json();
alert(data.message);
};
const handleDashboard = async () => {
const res = await fetch("http://localhost:5000/dashboard", {
method: "GET",
credentials: "include"
});
const data = await res.json();
setDashboardMsg(data.message);
};
const handleLogout = async () => {
const res = await fetch("http://localhost:5000/logout", {
method: "POST",
credentials: "include"
});
const data = await res.json();
alert(data.message);
setDashboardMsg("");
};
return (
<div style={{ margin: "20px", fontFamily: "Arial" }}>
<h2>Signup</h2>
<input type="text" placeholder="Username" value={signupUser} onChange={(e) => setSignupUser(e.target.value)} />
<input type="password" placeholder="Password" value={signupPass} onChange={(e) => setSignupPass(e.target.value)} />
<button onClick={handleSignup}>Signup</button>
<h2>Login</h2>
<input type="text" placeholder="Username" value={loginUser} onChange={(e) => setLoginUser(e.target.value)} />
<input type="password" placeholder="Password" value={loginPass} onChange={(e) => setLoginPass(e.target.value)} />
<button onClick={handleLogin}>Login</button>
<h2>Dashboard</h2>
<button onClick={handleDashboard}>View Dashboard</button>
<p>{dashboardMsg}</p>
<h2>Logout</h2>
<button onClick={handleLogout}>Logout</button>
</div>
);
}
export default App;
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/ping", (req, res) => {
res.send("pong");
});
app.listen(PORT, () => {
console.log(`Ping server running at http://localhost:${PORT}`);
});
{
"name": "ping-server",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2"
}
}
FROM node:18
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
import React, { useState } from "react";
function App() {
const [response, setResponse] = useState("");
const handlePing = async () => {
try {
const res = await fetch("http://localhost:3000/ping");
const text = await res.text();
setResponse(text);
} catch (err) {
setResponse("Error: " + err.message);
}
};
return (
<div style={{ textAlign: "center", marginTop: "50px", fontFamily: "Arial" }}>
<h1>Ping Server Test</h1>
<button onClick={handlePing} style={{ padding: "10px 20px", fontSize: "16px" }}>
Send Ping
</button>
<p style={{ marginTop: "20px", fontSize: "18px" }}>
Response: {response}
</p>
</div>
);
}
export default App;
import React from "react";
export default function Header() {
return (
<header style={{ padding: "20px", textAlign: "center", background: "#282c34", color: "white" }}>
<h1>My SaaS App</h1>
<p>Choose a plan that fits your needs</p>
</header>
);
}
import React from "react";
export default function PricingCard({ plan, price, features }) {
return (
<div style={{ border: "1px solid #ddd", padding: "20px", borderRadius: "8px", width: "250px" }}>
<h2>{plan}</h2>
<h3>${price}/month</h3>
<ul>
{features.map((feature, index) => (
<li key={index}>{feature}</li>
))}
</ul>
<button style={{ padding: "10px", background: "#61dafb", border: "none", borderRadius: "5px" }}>
Subscribe
</button>
</div>
);
}
import React from "react";
import Header from "./components/Header";
import PricingCard from "./components/PricingCard";
import "./App.css";
function App() {
const plans = [
{ plan: "Basic", price: 10, features: ["Feature A", "Feature B"] },
{ plan: "Pro", price: 20, features: ["Feature A", "Feature B", "Feature C"] },
{ plan: "Enterprise", price: 50, features: ["All Features", "Priority Support"] },
];
return (
<div>
<Header />
<div style={{ display: "flex", justifyContent: "center", gap: "20px", marginTop: "20px" }}>
{plans.map((plan, index) => (
<PricingCard key={index} {...plan} />
))}
</div>
</div>
);
}
export default App;
import React, { useState } from "react";
const withSearch = (WrappedComponent) => {
return function WithSearch(props) {
const [query, setQuery] = useState("");
const handleChange = (e) => {
setQuery(e.target.value);
};
return <WrappedComponent query={query} onChange={handleChange} {...props} />;
};
};
export default withSearch;
import React from "react";
export default function SearchBar({ query, onChange }) {
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<input
type="text"
value={query}
onChange={onChange}
placeholder="Search Google..."
style={{
width: "400px",
padding: "10px",
fontSize: "18px",
borderRadius: "5px",
border: "1px solid #ccc",
}}
/>
</div>
);
}
import React from "react";
import SearchBar from "./SearchBar";
import withSearch from "../hoc/withSearch";
function GoogleSearch({ query, onChange }) {
return (
<div>
<h2 style={{ textAlign: "center" }}>Google Search Example (HOC)</h2>
<SearchBar query={query} onChange={onChange} />
{query && (
<p style={{ textAlign: "center", marginTop: "20px" }}>
You searched for: <strong>{query}</strong>
</p>
)}
</div>
);
}
export default withSearch(GoogleSearch);
import React from "react";
import GoogleSearch from "./components/GoogleSearch";
function App() {
return (
<div>
<GoogleSearch />
</div>
);
}
export default App;