0% found this document useful (0 votes)
4 views9 pages

Full Stack Lab Programs

This document outlines a series of lab programs focused on Full Stack Development using ExpressJS and ReactJS. It includes examples of routing, CRUD operations, middleware, templating, session management, user authentication, and database interactions with MongoDB. Additionally, it covers ReactJS concepts such as components, props, state management, event handling, and routing with React Router.
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)
4 views9 pages

Full Stack Lab Programs

This document outlines a series of lab programs focused on Full Stack Development using ExpressJS and ReactJS. It includes examples of routing, CRUD operations, middleware, templating, session management, user authentication, and database interactions with MongoDB. Additionally, it covers ReactJS concepts such as components, props, state management, event handling, and routing with React Router.
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/ 9

FULL STACK DEVELOPMENT

– LAB PROGRAMS (Record Submission)

1. ExpressJS – Routing, HTTP Methods, Middleware


a) Write a program to define a route, Handling Routes, Route Parameters, Query
Parameters and URL building.
// express-routing.js
const express = require('express');
const app = express();

// Basic Route
app.get('/', (req, res) => res.send('Hello World'));

// Route with parameter


app.get('/user/:id', (req, res) => res.send(`User ID: ${req.params.id}`));

// Query parameter
app.get('/search', (req, res) => res.send(`Search term: ${req.query.q}`));

app.listen(3000, () => console.log("Server running at http://localhost:3000"));

b) Write a program to accept data, retrieve data and delete a specified resource using
HTTP methods.
// express-crud.js
const express = require('express');
const app = express();
app.use(express.json());

let users = [{ id: 1, name: "John" }];

// POST - Create
app.post('/users', (req, res) => {
users.push(req.body);
res.send(users);
});

// GET - Read
app.get('/users', (req, res) => res.send(users));

// DELETE - Delete
app.delete('/users/:id', (req, res) => {
users = users.filter(u => u.id != req.params.id);
res.send(users);
});

app.listen(3000, () => console.log("CRUD server running..."));

c) Write a program to show the working of middleware.


// express-middleware.js
const express = require('express');
const app = express();

// Middleware function
app.use((req, res, next) => {
console.log(`Request Method: ${req.method}, URL: ${req.url}`);
next(); // pass control
});

app.get('/', (req, res) => res.send('Middleware Example'));

app.listen(3000, () => console.log("Middleware server running..."));

2. ExpressJS – Templating, Form Data


a) Write a program using templating engine.
// ejs-example.js
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {


res.render('index', { name: "John" });
});

app.listen(3000, () => console.log("EJS Example running..."));

views/index.ejs

<h1>Hello <%= name %></h1>

b) Write a program to work with form data.


// form-data.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {


res.send('<form method="post"><input name="name"/><button>Submit</button></form>');
});

app.post('/', (req, res) => {


res.send(`You entered: ${req.body.name}`);
});

app.listen(3000, () => console.log("Form data example running..."));

3. ExpressJS – Cookies, Sessions, Authentication


a) Write a program for session management using cookies and sessions.
// session-example.js
const express = require('express');
const session = require('express-session');
const app = express();

app.use(session({ secret: "secret", saveUninitialized: true, resave: true }));

app.get('/set', (req, res) => {


req.session.user = "John";
res.send("Session set!");
});

app.get('/get', (req, res) => {


res.send(`Hello ${req.session.user}`);
});

app.listen(3000, () => console.log("Session Example running..."));

b) Write a program for user authentication.


// auth-example.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());

const users = { admin: "123" };

app.post('/login', (req, res) => {


const { username, password } = req.body;
if (users[username] && users[username] === password) {
res.send("Login Successful");
} else {
res.send("Invalid Credentials");
}
});

app.listen(3000, () => console.log("Authentication Example running..."));

4. ExpressJS – Database, RESTful APIs


a) Write a program to connect MongoDB database using Mongoose and perform CRUD
operations.
// mongoose-crud.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());

mongoose.connect("mongodb://localhost:27017/test");

const User = mongoose.model("User", { name: String, age: Number });

// CREATE
app.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.send(user);
});

// READ
app.get('/users', async (req, res) => res.send(await User.find()));
// UPDATE
app.put('/users/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(user);
});

// DELETE
app.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.send("User Deleted");
});

app.listen(3000, () => console.log("Mongoose CRUD running..."));

b) Write a program to develop a single page application using RESTful APIs.

�This is similar to above, where ReactJS frontend consumes ExpressJS API.


(Sample React fetch)

useEffect(() => {
fetch("http://localhost:3000/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []);

5. ReactJS – Render HTML, JSX, Components


a) Write a program to render HTML to a web page.
function App() {
return <h1>Hello World</h1>;
}
export default App;

b) Write a program for writing markup with JSX.


const element = <h2>{5+5}</h2>;

c) Write a program for creating and nesting components.


function Child() {
return <h2>Child Component</h2>;
}

function Parent() {
return (
<div>
<h1>Parent Component</h1>
<Child />
</div>
);
}
6. ReactJS – Props and States, Styles, Respond to Events
a) Write a program to work with props and states.
// PropsExample.js
function Welcome(props) {
return <h2>Hello {props.name}</h2>;
}

// State Example
import { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}

export { Welcome, Counter };

b) Write a program to add styles (CSS & Sass Styling) and display data.
// StylesExample.js
import "./App.css";

function StyledText() {
return <h2 className="redText">This is styled text</h2>;
}

export default StyledText;

App.css

.redText {
color: red;
font-size: 24px;
}

c) Write a program for responding to events.


// EventExample.js
function EventExample() {
const handleClick = () => alert("Button Clicked!");
return <button onClick={handleClick}>Click Me</button>;
}
export default EventExample;

7. ReactJS – Conditional Rendering, Rendering Lists, React Forms


a) Write a program for conditional rendering.
function Conditional() {
const loggedIn = true;
return (
<>
{loggedIn ? <h2>Welcome User</h2> : <h2>Please Login</h2>}
</>
);
}
export default Conditional;

b) Write a program for rendering lists.


function ListExample() {
const items = ["Apple", "Banana", "Cherry"];
return (
<ul>
{items.map((item, i) => <li key={i}>{item}</li>)}
</ul>
);
}
export default ListExample;

c) Write a program for working with different form fields using React forms.
import { useState } from "react";

function FormExample() {
const [form, setForm] = useState({ name: "", email: "" });

const handleChange = (e) =>


setForm({ ...form, [e.target.name]: e.target.value });

const handleSubmit = (e) => {


e.preventDefault();
alert(`Name: ${form.name}, Email: ${form.email}`);
};

return (
<form onSubmit={handleSubmit}>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
<button>Submit</button>
</form>
);
}

export default FormExample;

8. ReactJS – React Router, Updating the Screen


a) Write a program for routing to different pages using React Router.
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function Home() { return <h2>Home Page</h2>; }


function About() { return <h2>About Page</h2>; }

function App() {
return (
<BrowserRouter>
<nav>
<Link to="/home">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
export default App;

b) Write a program for updating the screen.


import { useState } from "react";

function UpdateExample() {
const [text, setText] = useState("Hello");
return (
<>
<h2>{text}</h2>
<button onClick={() => setText("Updated Text!")}>Update</button>
</>
);
}
export default UpdateExample;

9. ReactJS – Hooks, Sharing Data between Components


a) Write a program to understand the importance of using hooks.
import { useState, useEffect } from "react";

function HookExample() {
const [count, setCount] = useState(0);

useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);

return <button onClick={() => setCount(count + 1)}>Click {count}</button>;


}

export default HookExample;

b) Write a program for sharing data between components.


function Child({ message }) {
return <h2>Message: {message}</h2>;
}

function Parent() {
return <Child message="Hello from Parent" />;
}
export default Parent;

10. MongoDB – Installation, Configuration, CRUD Operations


a) Install MongoDB and configure ATLAS
�(Setup step, no code. Use mongosh for CLI)

b) Write MongoDB queries to perform CRUD operations.


// Insert
db.users.insertOne({ name: "John", age: 25 });

// Find
db.users.find();

// Update
db.users.updateOne({ name: "John" }, { $set: { age: 30 } });

// Delete
db.users.deleteOne({ name: "John" });

11. MongoDB – Databases, Collections and Records


a) Create and Drop databases/collections.
// Create Database
use mydb

// Create Collection
db.createCollection("students")

// Drop Database
db.dropDatabase()

// Drop Collection
db.students.drop()

b) Work with records using queries.


// Insert Multiple
db.students.insertMany([{name:"A",age:20}, {name:"B",age:22}]);

// Find with Limit


db.students.find().limit(1);

// Sort
db.students.find().sort({age:1});

// Create Index
db.students.createIndex({name:1});

// Aggregate
db.students.aggregate([{ $group: { _id: null, avgAge: { $avg: "$age" } } }]);

12. Augmented Programs (Any 2)


a) Design a To-do list application using NodeJS and ExpressJS
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/todo');
const Task = mongoose.model('Task', { text: String });

// Add Task
app.post('/tasks', async (req, res) => {
const task = new Task(req.body);
await task.save();
res.send(task);
});

// View Tasks
app.get('/tasks', async (req, res) => {
res.send(await Task.find());
});

// Delete Task
app.delete('/tasks/:id', async (req, res) => {
await Task.findByIdAndDelete(req.params.id);
res.send("Task Deleted");
});

app.listen(3000, () => console.log("To-do App running..."));

b) Design a Quiz application using NodeJS and ExpressJS


const express = require('express');
const app = express();
app.use(express.json());

let questions = [
{ q: "2+2=?", a: "4" },
{ q: "Capital of India?", a: "Delhi" }
];

app.get('/quiz', (req, res) => res.send(questions));

app.post('/quiz', (req, res) => {


const { q, a } = req.body;
questions.push({ q, a });
res.send("Question Added");
});

app.listen(3000, () => console.log("Quiz App running..."));

You might also like