FSD - II - Lab Manual
FSD - II - Lab Manual
Check again:
node -v
# should say "command not found"
node -v
# should be v18.x.x
cd ~/Desktop/23MG1A0593
rm -rf node_modules package-lock.json
npm install
node Program1.js
2. Install Express
Run the following command in your terminal:
npm install express
This downloads and installs Express and adds it to your package.json dependencies.
// Root Route
app.get('/', (req, res) => {
res.send('Welcome to the Express.js Demo!');
});
// 404 handler
app.use((req, res) => {
res.status(404).send('Route not found.');
});
➢ http://localhost:3000/
➢ http://localhost:3000/user/42
➢ http://localhost:3000/user/42/post/88
➢ http://localhost:3000/search?q=express&page=2
➢ http://localhost:3000/build-url
const id = String(nextId++);
const item = { id, name };
items[id] = item;
delete items[id];
res.json({ message: `Item ${id} deleted` });
});
app.listen(PORT, () => {
console.log(`✅ Server running at http://localhost:${PORT}`);
});
// 4. Another route
app.get('/test', (req, res) => {
res.send('Hello from /test route!');
});
app.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`);
});
Folder Structure
project-folder/
│
├── views/
│ ├── form.ejs # Input form
│ └── result.ejs # Display submitted data
│
└── app.js # Express app
app.js
c
o
n
st
e
x
p
r
e
s
s
=
r
e
q
u
ir
e
('
e
x
p
r
e
s
s'
);
c
o
(
)
=
>
{
console.log(`Server is running at http://localhost:
${port}`);
});
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
views/result.ejs
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<body>
<h1>Form Submitted</h1>
<p><strong>Name:</strong> <%= name %></p>
<p><strong>Email:</strong> <%= email %></p>
</body>
</html>
How to Run
npm init -y
npm install express ejs
1. Start your server:
node app.js
2. Open your browser and visit: http://localhost:3000
// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
npm init -y
npm install express express-session cookie-parser
// Session configuration
app.use(session({
secret: 'mySecretKey', // Secret for signing the session ID cookie
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something is stored
cookie: { maxAge: 60000 } // Session expires after 1 minute
}));
// Dummy credentials
const USERNAME = 'admin';
const PASSWORD = '12345';
// Home/Login Page
app.get('/', (req, res) => {
if (req.session.username)
{ res.send(`
<h2>Welcome, ${req.session.username}</h2>
<p>Last Login: ${req.cookies.lastLogin || 'First time!'}</p>
<a href="/logout">Logout</a>
`);
} else {
res.send(`
<h2>Login</h2>
<form method="POST" action="/login">
Username: <input type="text" name="username" required /><br><br>
Password: <input type="password" name="password" required /><br><br>
<button type="submit">Login</button>
res.redirect('/');
} else {
res.send('Invalid credentials. <a href="/">Try again</a>');
}
});
// Logout Handler
app.get('/logout', (req, res) => {
res.clearCookie('lastLogin'); // Clear cookie
req.session.destroy(() => { // Destroy session
res.redirect('/');
});
});
// Start Server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret: 'mySecretKey', // Secret to sign the session ID cookie
resave: false, // Don't save session if not modified
saveUninitialized: false, // Don't create empty sessions
cookie: { maxAge: 60000 } // Session expires in 1 minute
}));
// Login Handler
app.post('/login', (req, res) => {
const { username, password } = req.body;
res.redirect('/');
} else {
res.send('Invalid username or password. <a href="/">Try again</a>');
}
});
// Logout Handler
app.get('/logout', (req, res) => {
res.clearCookie('lastLogin'); // Remove cookie
req.session.destroy(() => { // Remove session
res.redirect('/');
});
});
// Start server
app.listen(PORT, () => {
console.log(`Authentication app running at http://localhost:${PORT}`);
});
project-folder/
├── public/
│ └── index.html ← (Your HTML file goes here)
├── server.js ← (Your Express + MongoDB server)
├── .env ← (Your environment variables)
└── package.json
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>MongoDB CRUD UI</title>
<style>
body { font-family: Arial, sans-serif; max-width: 700px; margin: 2em auto; }
input, button { padding: 0.5em; margin: 0.2em 0; width: 100%; }
.user-item { border-bottom: 1px solid #ccc; padding: 0.5em 0; }
</style>
</head>
<body>
<h1>Users CRUD Interface</h1>
<h2>Create User</h2>
<form id="createUserForm">
<input type="text" id="name" placeholder="Name" required />
<input type="email" id="email" placeholder="Email" required />
<input type="number" id="age" placeholder="Age" min="0" />
<button type="submit">Create User</button>
</form>
<h2>All Users</h2>
<button id="refreshBtn">Refresh List</button>
<div id="usersList"></div>
<script>
const apiBase = '/users';
users.forEach(user => {
const div = document.createElement('div');
// Create user
document.getElementById('createUserForm').addEventListener('submit', async e =>
{
e.preventDefault();
const name = document.getElementById('name').value.trim();
const email = document.getElementById('email').value.trim();
const age = parseInt(document.getElementById('age').value);
if (res.ok) {
alert('User created!');
e.target.reset();
fetchUsers();
} else {
const error = await res.json();
alert('Error: ' + error.error);
}
});
// Delete user
async function deleteUser(id) {
if (!confirm('Delete this user?')) return;
const res = await fetch(`${apiBase}/${id}`, { method: 'DELETE' });
if (res.ok) {
alert('User deleted');
fetchUsers();
} else {
alert('Delete failed');
// Update user
async function updateUser(id) {
const name = document.getElementById(`updateName-${id}`).value.trim();
const email = document.getElementById(`updateEmail-${id}`).value.trim();
const age = parseInt(document.getElementById(`updateAge-${id}`).value);
if (res.ok) {
alert('User updated!');
hideUpdateForm(id);
fetchUsers();
} else {
const error = await res.json();
alert('Error: ' + error.error);
}
}
// Initial load
fetchUsers();
document.getElementById('refreshBtn').addEventListener('click', fetchUsers);
</script>
</body>
</html>
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
app.use(express.json());
if (!mongoURI) {
console.error('❌ MONGODB_URI not defined in .env');
process.exit(1);
}
mongoose.connect(mongoURI)
.then(() => console.log('✅ MongoDB connected'))
.catch(err => {
console.error('❌ MongoDB connection error:', err.message);
process.exit(1);
});
MONGODB_URI=mongodb://127.0.0.1:27017/myd
//src/index.js
import React, { useState } from 'react'; function App() {
const [username, setUsername] = useState('');
const [submittedName, setSubmittedName] = useState('');
const handleChange = (event) => {
setUsername(event.target.value);
};
const handleSubmit = (event) =>
{ event.preventDefault();
setSubmittedName(username); setUsername('');
};
return (
<div>
{!submittedName ? (
<form onSubmit={handleSubmit}>
<input type="text"
placeholder="Enter your name"
value={username}
onChange={handleChang
e} required
/>
<button type="submit">Submit</button>
</form>
):(
<>
<h1>Welcome, {submittedName}!</h1>
<p>This is written using JSX syntax.</p>
</>
)}
</div>
);
}
export default App;
jsx
import React from 'react'; function Child() {
return <p>This is a Function Child Component!</p>;
}
export default Child;
jsx
import React, { Component } from 'react'; class Sibling extends Component {
render() {
return <p>This is a Class Sibling Component!</p>;
}
}
export default Sibling;
jsx
import React from 'react'; import Child from './Child'; import Sibling from
'./Sibling'; function Parent() {
return (
<div>
<h2>This is the Parent Function Component</h2>
<Child />
<Sibling />
</div>
);
}
export default Parent;
jsx
import React from 'react'; import Parent from './Parent'; function App() {
return (
<div>
<h1>React Component Nesting Example</h1>
<Parent />
</div>
);
}
export default App;
Step - 5
● Visit http://localhost:3000
Step-1
● sudo apt update
● sudo apt install nodejs npm
Step-5
● Open browser at http://localhost:3000
from "react";
import
"./App.css";
function App() {
const data = ["React", "CSS", "Sass", "JavaScript"]; return (
<div className="container">
<h1 className="title">Styling in React</h1>
<ul>
{data.map((item) => (
<li key={item} className="list-item">{item}</li>
))}
</ul>
</div>
);
}
export default App;
src/App.css
.container {
background-color: #282c34; padding: 20px;
color: #61dafb;
font-family: Arial, sans-serif;
}
.title {
font-size: 2rem; margin-bottom: 10px;
}
.list-item {
font-size: 1.2rem; margin: 5px 0;
Step-4
Open browser at http://localhost:3000
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? "Log Out" : "Log In"}
</button>
<h1>{isLoggedIn ? "Welcome Back!" : "Please Sign In"}</h1>
</div>
);
}
function App() {
const fruits = ["Apple", "Banana", "Cherry"];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
// src/App.js
import React, { useState } from "react";
function App() {
const [formData, setFormData] = useState({
name: "",
email: "",
subscribe: false,
});
function handleChange(event) {
const { name, value, type, checked } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: type === "checkbox" ? checked : value,
}));
}
function handleSubmit(event) {
event.preventDefault();
alert(`Form Data:\n${JSON.stringify(formData, null, 2)}`);
}
return (
<form onSubmit={handleSubmit}>
<div>
<label>
Name:
<input
name="name"
value={formData.name}
onChange={handleChange}
type="text"
/>
</label>
</div>
<div>
<label>
Email:
<input
name="email"
value={formData.email}
onChange={handleChange}
type="email"
/>
// Page component that receives 'topic' param from URL and displays info
function Page() {
const { topic } = useParams();
return (
<div>
<h1>Page for {topic}</h1>
<p>Here is some information about <strong>{topic}</strong>.</p>
<Link to="/">Back to Home</Link>
</div>
);
}
function Counter() {
// Declare a state variable 'count', initial value 0
const [count, setCount] = useState(0);
return (
<div>
<h2>Counter Value: {count}</h2>
<button onClick={handleIncrement}>Increment</button>
</div>
);
}