0% found this document useful (0 votes)
21 views31 pages

Fullstack Lab

The document provides an extensive overview of Express.js, a web application framework for Node.js, detailing its features such as middleware, routing, and template engines. It includes practical experiments demonstrating routing, handling HTTP methods, middleware usage, templating with EJS, form data processing, session management, user authentication, and CRUD operations with MongoDB. The document serves as a comprehensive guide for developers to understand and implement various functionalities using Express.js.

Uploaded by

lakshmimahaa999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views31 pages

Fullstack Lab

The document provides an extensive overview of Express.js, a web application framework for Node.js, detailing its features such as middleware, routing, and template engines. It includes practical experiments demonstrating routing, handling HTTP methods, middleware usage, templating with EJS, form data processing, session management, user authentication, and CRUD operations with MongoDB. The document serves as a comprehensive guide for developers to understand and implement various functionalities using Express.js.

Uploaded by

lakshmimahaa999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to EXPRESS:

Express.js is a streamlined web application framework for Node.js designed to facilitate


the creation of web applications and APIs. It extends Node.js's core features, providing a
structured approach to managing server-side logic. Known for its minimalistic approach,
Express offers essential web application functionalities by default and enables
developers to extend its features with middleware and plugins.

1. Middleware: Middleware is essential in Express. It allows you to modify request


and response objects, add processing logic, and handle errors effectively.
2. Routing: Express offers a powerful routing mechanism to define application
endpoints and handle various HTTP methods (GET, POST, PUT, DELETE, etc.).
This feature simplifies the process of building RESTful APIs.
3. Template Engines: Express supports various templating engines, such as Pug,
EJS, and Handlebars. These engines enable you to generate dynamic HTML
content on the server side.
4. Extensibility: Express is highly extensible and can be integrated with numerous
third-party libraries and tools. This flexibility allows you to easily add features like
authentication, validation, and logging.
5. Performance: Built on Node.js's asynchronous, non-blocking architecture,
Express performs well when handling multiple simultaneous connections.

Experiment1: -

ExpressJS -Routing, HTTP Methods, Middleware.

a). Write a program to define a route, Handling Routes, Route parameters, Query Parameters and
URL building.

Define Route:

Routing in Express.js defines URL patterns (endpoints) and links them with specific
actions or resources within your web application. It allows users to navigate your
application based on URLs. Express uses the app object to define routes.
app.METHOD(PATH, HANDLER)
Each route consists of three parts:

 METHOD: Specifies the HTTP request method. Common methods include GET,
POST, PUT, DELETE, etc.
 PATH: Defines the URL pattern for the route. (e.g., /about, /contact).
 HANDLER: The function that is executed when a route is matched. It typically
sends a response back to the client.

Route Parameters:

In Express.js, route parameters are parts of the URL defined to capture dynamic
values. These parameters are specified in the route path by prefixing a colon (:) before
the parameter name. When a request is made to a route that includes parameters,
Express.js extracts these values and makes them available in the req.params object.
app.get('/users/:userId', (req, res) => {
Query Parameter:
In Express.js, query parameters are used to pass data to the server through the URL. They
are typically appended to the URL after a? and are key-value pairs separated by &.

Source Code

const express = require('express');

const app = express();

app.listen(3000,() => {

console.log (`server is running on port 3000`);

});

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

res.send(`Helo World!`);

});

app.get(`/api/:name`,(req,res) => {

const name=req.params.name;

res.send(`hello,${name});

});

app.get(‘/j’,(req,res) => {

const query = req.query.j;

res.sen(query);

});

Output:
b). Write a Program to accepted data, retrieve data and delete a specified resource using HTTP
methods.

Express.js allows you to define route handlers for various HTTP methods. Below are
examples of handling common HTTP requests like GET, POST, PUT, and DELETE.

You use a GET request to retrieve data from the server.


The POST method sends data to the server, typically when creating a new record.
You use a PUT request to update existing data.
DELETE requests remove data from the server.

Source Code:

const express = require('express');

const bodyParser = require('body-parser');

const fs = require('fs');

const app = express();

const PORT = 3000;

const FILE_PATH = './data.txt';

app.use(bodyParser.json());

// Helper: Read data from the file

function readData() {

if (!fs.existsSync(FILE_PATH)) return [];

const content = fs.readFileSync(FILE_PATH, 'utf8');

return content ? JSON.parse(content) : [];

// Helper: Write data to the file

function writeData(data) {

fs.writeFileSync(FILE_PATH, JSON.stringify(data, null, 2));

// POST: Add new data

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

const newData = req.body;

const data = readData();


data.push(newData);

writeData(data);

res.status(201).json({ message: 'Data added successfully', data: newData });

});

// GET: Retrieve all data

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

const data = readData();

res.json(data);

});

// DELETE: Delete data by ID

app.delete('/data/:id', (req, res) => {

const id = req.params.id;

let data = readData();

const initialLength = data.length;

data = data.filter(item => item.id !== id);

if (data.length === initialLength) {

return res.status(404).json({ message: 'Data not found' });

writeData(data);

res.json({ message: `Data with id ${id} deleted successfully` });

});

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${PORT}`);

});

create a text file with name data.txt


[

"id": "1",

"name": "Alice"

To run program

open command prompt and check curl --version is their or not

for retrieving data

Type the command in command prompt

curl http://localhost:3000/data

Deleting the data

Type the command in command prompt

curl -X DELETE http://localhost:3000/2

1c). Write a program to show the working of Middleware.

Custom middleware is a user-defined function (like a checkpoint) that each


request passes through before reaching your route. With custom middleware, you can
intercept requests, run your code, and then decide what to do next: let the request
continue to the next middleware or route handler, or stop it and send back the response.
A custom middleware typically has three parameters:

 req: The request object.


 res: The response object.
 next: A function to pass control to the next middleware in the stack.

function customMiddleware(req, res, next) {


// Your custom logic here
console.log('Custom middleware running');
next(); // Move to the next middleware or route
}
Source Code:

const express = require('express');

const app = express();

const port = 3000;

// Middleware function to check if user is authenticated (dummy example)

function authMiddleware(req, res, next) {

const isAuthenticated = true; // For demo, set true or false to test

if (isAuthenticated) {

next();

} else {

res.status(401).send('Unauthorized');

// Define a public route

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

res.send('Welcome to the public page!');

});

// Use auth middleware for protected routes

app.use('/protected', authMiddleware);

// Protected route

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

res.send('This is a protected page. You are authenticated.');

});

// Start server

app. listen (port, () => {

console.log (`Server running on http://localhost:${port}`);


});

Output:
Experiment2: -

ExpressJS - Templating, Form Data

Templating Data:

Templating data refers to the process of injecting dynamic data into a predefined template
(usually HTML or text) to generate a final rendered output. The template contains
placeholders or variables that are replaced at runtime with actual values, allowing the creation
of customized content based on data.

Templating Engines in Express

1. EJS (Embedded JavaScript)


2. Pug (formerly Jade)
3. Handlebars

Form Data

Form data is the information that a user enters into an HTML form, which is then sent to a web
server when the form is submitted. This data usually consists of values from input fields like text
boxes, checkboxes, radio buttons, selects, and others.

2(a). Write a program using Templating engine.

const express = require('express');

const app = express();

const port = 3000;

// Set EJS as templating engine

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

// Middleware to parse form data (URL-encoded)

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

// Route to show form

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

res.render('form');

});

// Route to handle form POST submission


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

const { name, email } = req.body;

res.render('result', { name, email });

});

// Start server

app.listen(port, () => {

console.log(`Server running at http://localhost:${port}`);

});

<!DOCTYPE html>

<html>

<head>

<title>User Form</title>

</head>

<body>

<h1>Enter Your Details</h1>

<form action="/submit" method="POST">

<label>Name:</label><br />

<input type="text" name="name" required /><br /><br />

<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>Submission Result</title>

</head>

<body>

<h1>Submitted Data</h1>

<p><strong>Name:</strong> <%= name %></p>

<p><strong>Email:</strong> <%= email %></p>

<a href="/">Back to form</a>

</body>

</html>

Output:
2(b). Write a program to work with form data.

const express = require('express');


const app = express();

const port = 3000;

// Set EJS as the templating engine

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

// Define a route

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

const user = {

name: "Lakshmi",

age: 25,

country: "India"

};

res.render('index', { user: user });

});

// Start the server

app.listen(port, () => {

console.log(`Server running at http://localhost:${port}`);

});

Views/Index.ejs

<!DOCTYPE html>

<html>

<head>

<title>Templating Example</title>

</head>

<body>

<h1>Welcome, <%= user.name %>!</h1>

<p>Age: <%= user.age %></p>

<p>Country: <%= user.country %></p>

</body>
</html>

Output:

Experiment:3

ExpressJS- Cookies, Sessions, Authentication.

Cookie:

cookies are small pieces of data that a web server sends to a user's web browser, and the browser
stores them. These cookies are then sent back to the server with subsequent requests, allowing the
server to "remember" information about the user or their session.

Sessions:

a session represents a way to store user-specific data on the server, allowing for stateful interactions
over the inherently stateless HTTP protocol.

Authentication:

authentication is the process of verifying the identity of a user, ensuring they are who they claim to
be. This is a fundamental security measure for web applications, as it prevents unauthorized access
to protected resources and functionalities.

3(a) Write a program for session management using cookies and sessions.

const express = require('express');

const session = require('express-session');

const cookieParser = require('cookie-parser');

const app = express();

const PORT = 3000;

// Middleware setup
app.use(cookieParser());

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

// Session configuration

app.use(session({

secret: 'mySecretKey', // use env variable in production

resave: false,

saveUninitialized: true,

cookie: { maxAge: 60000 } // 1 minute session

}));

// Route to show login form

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

res.send(`

<h2>Login</h2>

<form method="POST" action="/login">

<input type="text" name="username" placeholder="Enter username" required />

<button type="submit">Login</button>

</form>

`);

});

// Handle login form submission

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

const { username } = req.body;

// Save session data

req.session.username = username;

res.send(`<h2>Hello, ${username}!</h2><a href="/profile">Go to Profile</a>`);

});

// Protected route

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

if (req.session.username) {

res.send(`
<h2>Welcome to your profile, ${req.session.username}</h2>

<a href="/logout">Logout</a>

`);

} else {

res.send('<h2>Access Denied. Please <a href="/">login</a>.</h2>');

});

// Logout route

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

req.session.destroy(err => {

if (err) {

return res.send('Error logging out.');

res.clearCookie('connect.sid');

res.redirect('/');

});

});

// Start server

app.listen(PORT, () => {

console.log(`Server running on http://localhost:${PORT}`);

});

Output:
3(b). Write a program for User Authentication.

const express = require('express');

const bodyParser = require('body-parser');

const session = require('express-session');

const app = express();

const PORT = 3000;

// Middleware

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

app.use(session({

secret: 'your_secret_key',

resave: false,

saveUninitialized: true

}));
// Dummy user for authentication

const user = {

username: 'admin',

password: '1234'

};

// Home Route

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

if (req.session.user) {

res.send(`Welcome ${req.session.user.username} <br><a href="/logout">Logout</a>`);

} else {

res.send(`

<h2>Login</h2>

<form method="POST" action="/login">

<input type="text" name="username" placeholder="Username" required /><br>

<input type="password" name="password" placeholder="Password" required /><br>

<button type="submit">Login</button>

</form>

`);

});

// Login Route

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

const { username, password } = req.body;

if (username === user.username && password === user.password) {

req.session.user = user;

res.redirect('/');

} else {

res.send('Invalid credentials. <a href="/">Try again</a>');


}

});

// Logout Route

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

req.session.destroy();

res.redirect('/');

});

// Start server

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${PORT}`);

});s

Output:
Experiment 4:

ExpressJS-Database, RESTful APIs

RESTful API
REST (Representational State Transfer) is an architectural style for designing networked
applications using standard HTTP methods.

 GET – Read data


 POST – Create data
 PUT – Update data
 DELETE – Remove data

CRUD Operations

Basic operations of persistent storage:

Operation HTTP Method Description

Create POST Add new data

Read GET Get data

Update PUT/PATCH Modify existing data

Delete DELETE Remove data

MongoDB

A NoSQL database used to store data in a flexible, JSON-like format (documents).

Mongoose

An Object Data Modeling (ODM) library for MongoDB and Node.js.

 Connects Express.js to MongoDB


 Defines schemas and models for data structure
 Makes database operations easier

4(a). Write a program to connect MongoDB database using Mangoose and perform CURD
operations.
const express = require('express');

const mongoose = require('mongoose');

const bodyParser = require('body-parser');

const app = express();

const PORT = 3000;

// Middleware
app.use(bodyParser.json());

// Connect to MongoDB

mongoose.connect('mongodb://localhost:27017/studentDB')

.then(() => console.log("MongoDB connected"))

.catch(err => console.error("MongoDB connection error:", err));

// Schema and Model with custom id field

const studentSchema = new mongoose.Schema({

id: { type: String, required: true, unique: true }, // custom id

name: String,

age: Number,

course: String

});

const Student = mongoose.model('Student', studentSchema);

// --- CRUD Routes ---

// Create (POST)

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

try {

// Make sure req.body has 'id' property

if (!req.body.id) return res.status(400).send("Custom id is required");

const newStudent = new Student(req.body);

await newStudent.save();

res.status(201).send(newStudent);

console.log(`data added sucefully`)

} catch (err) {

res.status(400).send(err);

}
});

// Read all (GET)

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

try {

const students = await Student.find();

res.send(students);

} catch (err) {

res.status(500).send(err);

});

// Read one by custom id (GET)

app.get('/students/:id', async (req, res) => {

try {

const student = await Student.findOne({ id: req.params.id });

if (!student) return res.status(404).send("Student not found");

res.send(student);

} catch (err) {

res.status(500).send(err);

});

// Update by custom id (PUT)

app.put('/students/:id', async (req, res) => {

try {

const updatedStudent = await Student.findOneAndUpdate(

{ id: req.params.id },

req.body,

{ new: true }

);
if (!updatedStudent) return res.status(404).send("Student not found");

res.send(updatedStudent);

} catch (err) {

res.status(400).send(err);

});

// Delete by custom id (DELETE)

app.delete('/students/:id', async (req, res) => {

try {

const deletedStudent = await Student.findOneAndDelete({ id: req.params.id });

if (!deletedStudent) return res.status(404).send("Student not found");

res.send(deletedStudent);

console.log(`deleted data sucessfully`)

} catch (err) {

res.status(500).send(err);

});

// Start Server

app.listen(PORT, () => {

console.log(`Server running on http://localhost:${PORT}`);

});

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

const express = require('express');

const mongoose = require('mongoose');

const bodyParser = require('body-parser');

const path = require('path');

const app = express();

const PORT = 3000;


// Middleware

app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'public')));

// Connect to MongoDB

mongoose.connect('mongodb://localhost:27017/spaDB', {

useNewUrlParser: true,

useUnifiedTopology: true,

})

.then(() => console.log("MongoDB connected"))

.catch(err => console.error(err));

// Schema

const TaskSchema = new mongoose.Schema({

title: String,

completed: Boolean

});

const Task = mongoose.model('Task', TaskSchema);

// RESTful APIs

// Create

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

const task = new Task(req.body);

await task.save();

res.status(201).json(task);

});

// Read All

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


const tasks = await Task.find();

res.json(tasks);

});

// Update

app.put('/api/tasks/:id', async (req, res) => {

const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });

res.json(task);

});

// Delete

app.delete('/api/tasks/:id', async (req, res) => {

await Task.findByIdAndDelete(req.params.id);

res.json({ message: 'Deleted' });

});

// Start server

app.listen(PORT, () => {

console.log(`Server running at http://localhost:${PORT}`);

});

Forntend:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>SPA Task Manager</title>

<style>

body { font-family: Arial; margin: 20px; }

input, button { padding: 5px; margin: 5px; }

.completed { text-decoration: line-through; color: gray; }

</style>
</head>

<body>

<h2>Task Manager (SPA)</h2>

<input type="text" id="taskTitle" placeholder="New task">

<button onclick="addTask()">Add</button>

<ul id="taskList"></ul>

<script>

async function fetchTasks() {

const res = await fetch('/api/tasks');

const tasks = await res.json();

const list = document.getElementById('taskList');

list.innerHTML = '';

tasks.forEach(task => {

const li = document.createElement('li');

li.innerHTML = `

<span class="${task.completed ? 'completed' : ''}" onclick="toggleComplete('${task._id}',


${!task.completed})">

${task.title}

</span>

<button onclick="deleteTask('${task._id}')">Delete</button>

`;

list.appendChild(li);

});

async function addTask() {

const title = document.getElementById('taskTitle').value;

if (!title) return;

await fetch('/api/tasks', {
method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({ title, completed: false })

});

document.getElementById('taskTitle').value = '';

fetchTasks();

async function deleteTask(id) {

await fetch(`/api/tasks/${id}`, { method: 'DELETE' });

fetchTasks();

async function toggleComplete(id, newStatus) {

await fetch(`/api/tasks/${id}`, {

method: 'PUT',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({ completed: newStatus })

});

fetchTasks();

fetchTasks(); // Load on page load

</script>

</body>

</html>

Output:

You might also like