We'll create a basic Express server with the following:
GET / → Home route
GET /user/:id → Route parameter
GET /search → Query parameters
URL generation using res.redirect and req.originalUrl
npm init -y
npm install express
Command Description
npm Node Package Manager – used to manage packages/modules in Node.js projects
init Initializes a new Node.js project and creates a package.json file
-y or --yes Automatically fills in default values (name, version, etc.)
1. Project Structure
my-project/
│
├── index.js
└── public/
└── index.html
2. index.js Code (Express Server)
const express = require('express');
const app = express();
const port = 3000;
// Serve static files from the 'public' folder
app.use(express.static('public'));
app.get('/user/:id', (req, res) => {
res.send(`User ID is: ${req.params.id}`);
});
app.get('/search', (req, res) => {
const { keyword, page } = req.query;
res.send(`Searching for: ${keyword}, Page: ${page}`);
});
app.get('/goto-search', (req, res) => {
const keyword = 'express';
const page = 1;
res.redirect(`/search?keyword=${keyword}&page=${page}`);
});
app.get('/current-url', (req, res) => {
res.send(`Current URL is: ${req.originalUrl}`);
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>ExpressJS Route Links</title>
</head>
<body>
<h1>Welcome to ExpressJS Route Demo</h1>
<ul>
<li><a href="/user/123" target="_blank">Go to User with ID 123</a></li>
<li><a href="/search?keyword=nodejs&page=2" target="_blank">Search for nodejs (page 2)</a></li>
<li><a href="/goto-search" target="_blank">Redirect to Search</a></li>
<li><a href="/current-url" target="_blank">Show Current URL</a></li>
</ul>
</body>
</html>
3. Run Server
node index.js
http://localhost:3000
explanation
Defines routes
Handles route parameters
Handles query parameters
Redirects with URL building
Serves an HTML home page with clickable links
Opens links in new tabs
1. Project Structure
my-project/
├── index.js ← Main server file
└── public/
└── index.html ← Static HTML page with links
2. index.js – ExpressJS Server
const express = require('express'); // Loads the Express library
const app = express(); //Creates an app instance
const port = 3000; //Makes public/index.html available at http://localhost:3000/
// Serve static files like index.html from "public" folder
app.use(express.static('public'));
//Uses middleware express.static('public') to serve static HTML/CSS files
Route 1: /user/:id
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is: ${userId}`);
});
:id is a route parameter
If you visit /user/123, it captures 123 as req.params.id
Route 2: /search
app.get('/search', (req, res) => {
const { keyword, page } = req.query;
res.send(`Searching for: ${keyword}, Page: ${page}`);
});
Uses query parameters:
URL: /search?keyword=node&page=2
Accessed via req.query.keyword and req.query.page
Route 3: /goto-search
app.get('/goto-search', (req, res) => {
const keyword = 'express';
const page = 1;
const url = `/search?keyword=${keyword}&page=${page}`;
res.redirect(url);
});
Builds a URL dynamically
Redirects to /search?keyword=express&page=1 using res.redirect()
Route 4: /current-url
app.get('/current-url', (req, res) => {
res.send(`Current URL is: ${req.originalUrl}`);
});
req.originalUrl gives the full URL path that the client requested
Shows the exact route you accessed
Start the Server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
1. ExpressJS – Routing, HTTP Methods, Middleware
a. Write a program to define a route, handling routes, route parameters, query parameters, and URL
building.
b. Write a program to accept data, retrieve data, and delete a specified resource using HTTP methods.
c. Write a program to show the working of middleware.
2. ExpressJS – Templating, Form Data
a. Write a program using a templating engine.
b. Write a program to work with form data.
3. ExpressJS – Cookies, Sessions, Authentication
a. Write a program for session management using cookies and sessions.
b. Write a program for user authentication.
4. ExpressJS – Database, RESTful APIs
a. Write a program to connect MongoDB database using Mongoose and perform CRUD operations.
b. Write a program to develop a single page application using RESTful APIs.
5. ReactJS – Render HTML, JSX, Components – Function & Class
a. Write a program to render HTML to a web page.
b. Write a program for writing markup with JSX.
c. Write a program for creating and nesting components (function and class).
6. ReactJS – Props and States, Styles, Respond to Events
a. Write a program to work with props and states.
b. Write a program to add styles (CSS & Sass Styling) and display data.
c. Write a program for responding to events.
7. ReactJS – Conditional Rendering, Rendering Lists, React Forms
a. Write a program for conditional rendering.
b. Write a program for rendering lists.
c. Write a program for working with different form fields using react forms.
8. ReactJS – React Router, Updating the Screen
a. Write a program for routing to different pages using React Router.
b. Write a program for updating the screen.
9. ReactJS – Hooks, Sharing Data Between Components
a. Write a program to understand the importance of using hooks.
b. Write a program for sharing data between components.
10. MongoDB – Installation, Configuration, CRUD Operations
a. Install MongoDB and configure ATLAS.
b. Write MongoDB queries to perform CRUD operations on documents using insert(), find(),
update(), remove().
11. MongoDB – Databases, Collections and Records
a. Write MongoDB queries to create and drop databases and collections.
b. Write MongoDB queries to work with records using find(), limit(), sort(), createIndex(),
aggregate().
12. Augmented Programs (Any 2 must be completed)
a. Design a To-Do list application using NodeJS and ExpressJS.
b. Design a Quiz app using ReactJS.
c. Complete the MongoDB certification from MongoDB University website.
b. Write a program to accept data, retrieve data, and delete a specified resource using HTTP methods.
Accept data (POST)
Retrieve data (GET)
Delete a specific resource (DELETE)
1. Project Setup
npm init -y
npm install express
2. index.js – Main Server File
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse JSON data
app.use(express.json());
// Sample in-memory data store
let users = [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Jane Smith" }
];
// GET: Retrieve all users
app.get('/users', (req, res) => {
res.json(users);
});
// POST: Accept and add new user
app.post('/users', (req, res) => {
const { id, name } = req.body;
if (!id || !name) {
return res.status(400).json({ error: "id and name are required" });
// Check for duplicate ID
const exists = users.some(user => user.id === id);
if (exists) {
return res.status(409).json({ error: "User with this ID already exists" });
users.push({ id, name });
res.status(201).json({ message: "User added", user: { id, name } });
});
// DELETE: Remove user by ID
app.delete('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const index = users.findIndex(user => user.id === userId);
if (index === -1) {
return res.status(404).json({ error: "User not found" });
const removedUser = users.splice(index, 1);
res.json({ message: "User deleted", user: removedUser[0] });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
How to Test
🔸 GET all users
GET http://localhost:3000/users
POST a new user
POST http://localhost:3000/users
Content-Type: application/json
"id": 3,
"name": "Alice Johnson"
🔸 DELETE a user by ID
DELETE http://localhost:3000/users/2
Step-by-Step in Postman
Step 1: Open Postman
Launch the Postman app (or install it from postman.com).
Step 2: Select Method
Choose: POST
URL: http://localhost:3000/users
Step 3: Set Headers
Go to the "Headers" tab:
Key Value
Content-Type application/json
Step 4: Add JSON Body
1. Click on the "Body" tab
2. Select "raw"
3. Choose JSON (from dropdown on the right)
4. Paste this:
c. Write a program to show the working of middleware.
const express = require('express');
const app = express();
const port = 3000;
// Global middleware – logs every request
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // pass control to the next handler
});
// Middleware to simulate user authentication
const checkAuth = (req, res, next) => {
const isAuthenticated = true; // change this to false to simulate unauthorized
if (isAuthenticated) {
console.log(" User authenticated");
next();
} else {
res.status(401).send("❌ Unauthorized");
};
// Home route – always works
app.get('/', (req, res) => {
res.send("Welcome to the home page!");
});
// Protected route – uses checkAuth middleware
app.get('/dashboard', checkAuth, (req, res) => {
res.send("Welcome to your dashboard!");
});
// Middleware for handling 404
app.use((req, res) => {
res.status(404).send("❌ Page not found");
});
// Start server
app.listen(port, () => {
console.log(`🚀 Server running at http://localhost:${port}`);
});