Experiment 6: ExpressJS – Routing, HTTP Methods, Middleware

 6 Experiment 6: ExpressJS – Routing, HTTP Methods, Middleware



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


Below is a simple Express.js program that demonstrates:
  • Defining routes

  • Handling routes

  • Route parameters

  • Query parameters

  • URL building

1. Install Express


open command prompt


mkdir abc
cd abc

npm init -y
npm install express


2: Create app.js   ( Simple program to start with)


notepad app.js
                     
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Express routing working!');
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});


save and close.


3: Run Server


node app.js

Open browser:

type link or url :            http://localhost:3000   to see output


ROUTING AND QUERY PARAMETER EXAMPLE:



// Import express
const express = require('express');

// Create express app
const app = express();

// Port number
const PORT = 3000;

/* -------------------------
   1. Simple Route
-------------------------- */
app.get('/', (req, res) => {
    res.send('Welcome to Express Routing');
});

/* -------------------------
   2. Handling Routes
-------------------------- */
app.get('/about', (req, res) => {
    res.send('This is About Page');
});

/* -------------------------
   3. Route Parameters
   Example: /user/101
-------------------------- */
app.get('/user/:id', (req, res) => {
    const userId = req.params.id;
    res.send(`User ID is: ${userId}`);
});

/* -------------------------
   4. Query Parameters
   Example: /search?name=Ram&age=25
-------------------------- */
app.get('/search', (req, res) => {
    const name = req.query.name;
    const age = req.query.age;

    res.send(`Name: ${name}, Age: ${age}`);
});

/* -------------------------
   5. URL Building
-------------------------- */
app.get('/build-url', (req, res) => {
    const url = req.protocol + '://' + req.get('host') + '/user/100';
    res.send(`Generated URL: ${url}`);
});

/* -------------------------
   Start Server
-------------------------- */
app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});




Open browser and test:

  • http://localhost:3000/

  • http://localhost:3000/about

  • http://localhost:3000/user/10

  • http://localhost:3000/search?name=Ravi&age=30

Augmented Programming:



// Import express
const express = require('express');

// Create express app
const app = express();

// Port number
const PORT = 3000;

/* -------------------------
   User Data (Array of 3 Users)
-------------------------- */
const users = [
    { id: 1, name: "Raj", age: 30 },
    { id: 2, name: "Sita", age: 25 },
    { id: 3, name: "Manohar", age: 28 }
];

/* -------------------------
   1. Simple Route
-------------------------- */
app.get('/', (req, res) => {
    res.send('Welcome to Express Routing with Users');
});

/* -------------------------
   2. Handling Routes
-------------------------- */
app.get('/about', (req, res) => {
    res.send('This is About Page');
});

/* -------------------------
   3. Route Parameter
   Example: /user/2
-------------------------- */
app.get('/user/:id', (req, res) => {
    const userId = parseInt(req.params.id);

    const user = users.find(u => u.id === userId);

    if (user) {
        res.send(`ID: ${user.id}, Name: ${user.name}, Age: ${user.age}`);
    } else {
        res.send('User not found');
    }
});

/* -------------------------
   4. Query Parameters
   Example: /search?name=Ravi
-------------------------- */
app.get('/search', (req, res) => {
    const name = req.query.name;

    const user = users.find(
        u => u.name.toLowerCase() === name?.toLowerCase()
    );

    if (user) {
        res.send(`ID: ${user.id}, Name: ${user.name}, Age: ${user.age}`);
    } else {
        res.send('User not found');
    }
});

/* -------------------------
   5. Get All Users
   Example: /users
-------------------------- */
app.get('/users', (req, res) => {
    res.json(users);
});

/* -------------------------
   6. URL Building
-------------------------- */
app.get('/build-url', (req, res) => {
    const url = req.protocol + '://' + req.get('host') + '/user/1';
    res.send(`Generated URL: ${url}`);
});

/* -------------------------
   Start Server
-------------------------- */
app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});


Write a program to accept data, retrieve data and delete a specified resource using http methods. 


A Basic Express.js program that demonstrates how to:
  • Accept dataPOST (Create)

  • Retrieve dataGET (Read)

  • Delete a specified resourceDELETE (Delete)



Basic Express Server with HTTP Methods

// app.js
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware to read form data
app.use(express.urlencoded({ extended: true }));

let students = [];

/*
------------------------------------------------
GET : Home Page
------------------------------------------------
*/
app.get('/', (req, res) => {
    res.send(`
        <h2>Student Management</h2>
        <a href="/add">Add Student</a><br><br>
        <a href="/students">View Students</a>
    `);
});

/*
------------------------------------------------
GET : Show POST Form (Add Data)
------------------------------------------------
*/
app.get('/add', (req, res) => {
    res.send(`
        <h2>Add Student</h2>
        <form method="POST" action="/add">
            Name: <input type="text" name="name" required><br><br>
            Age: <input type="number" name="age" required><br><br>
            <button type="submit">Add Student</button>
        </form>
        <br>
        <a href="/">Home</a>
    `);
});

/*
------------------------------------------------
POST : Accept Data from Browser Form
------------------------------------------------
*/
app.post('/add', (req, res) => {
    const student = {
        id: students.length + 1,
        name: req.body.name,
        age: req.body.age
    };

    students.push(student);

    res.send(`
        <h3>Student Added Successfully</h3>
        <a href="/add">Add Another</a><br><br>
        <a href="/students">View Students</a>
    `);
});

/*
------------------------------------------------
GET : Retrieve Data
------------------------------------------------
*/
app.get('/students', (req, res) => {
    let output = `<h2>Student List</h2>`;

    if (students.length === 0) {
        output += `<p>No students found</p>`;
    } else {
        students.forEach(student => {
            output += `
                <p>
                    ID: ${student.id} |
                    Name: ${student.name} |
                    Age: ${student.age}
                </p>
                <form method="POST" action="/delete">
                    <input type="hidden" name="id" value="${student.id}">
                    <button type="submit">Delete</button>
                </form>
                <hr>
            `;
        });
    }

    output += `<br><a href="/">Home</a>`;
    res.send(output);
});

/*
------------------------------------------------
POST : Delete a Specified Resource (Browser)
------------------------------------------------
*/
app.post('/delete', (req, res) => {
    const id = parseInt(req.body.id);

    students = students.filter(student => student.id !== id);

    res.redirect('/students');
});

// Start Server
app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});




To start server

node app.js

To test

http://localhost:3000





Write a program to show the working of middleware. 




// app.js
const express = require('express');
const app = express();
const PORT = 3000;

/*
-----------------------------------------
Custom Middleware
-----------------------------------------
*/
const myMiddleware = (req, res, next) => {
    console.log("Middleware executed");
    console.log("Request URL:", req.url);
    console.log("Request Method:", req.method);
    next(); // Pass control to next middleware / route
};

/*
-----------------------------------------
Using Middleware
-----------------------------------------
*/
app.use(myMiddleware);

/*
-----------------------------------------
Route
-----------------------------------------
*/
app.get('/', (req, res) => {
    res.send("Hello! Middleware executed before this response.");
});

/*
-----------------------------------------
Another Route
-----------------------------------------
*/
app.get('/about', (req, res) => {
    res.send("About Page");
});

// Start Server
app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Consoleoutput:


Middleware executed
Request URL: /
Request Method: GET











Comments

Popular posts from this blog

Experiment 1: Node.js

Experiment 10: ReactJS – Render HTML, JSX, Components – function & Class