EXPERIMENT 1 - Express JS – Routing, HTTP Methods, Middleware.
(a) Write a program to define a route, Handling Routes, Route Parameters, Query
Parameters and URL building.
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Welcome to Express Routing!");
});
app.get("/user/:id", (req, res) => {
const userId = req.params.id;
res.send(`User ID is: ${userId}`);
});
app.get("/search", (req, res) => {
const keyword = req.query.keyword;
res.send(`You searched for: ${keyword}`);
});
app.get("/product/:category/:id", (req, res) => {
const { category, id } = req.params;
res.send(`Category: ${category}, Product ID: ${id}`);
});
app.listen(3000, () => {
console.log("Server started at http://localhost:3000");
});
Output
http://localhost:3000/ → Welcome to Express Routing!
http://localhost:3000/user/101 → User ID is: 101
http://localhost:3000/search?keyword=laptop → You searched for: laptop
http://localhost:3000/product/electronics/555 → Category: electronics, Product ID: 555
1(b) Write a program to accept data, retrieve data and delete a specified resource using http
methods.
const express = require("express");
const app = express();
app.use(express.json()); // to parse JSON body
let students = []; // In-memory array
app.post("/students", (req, res) => {
const student = req.body;
students.push(student);
res.send("Student added successfully!");
});
app.get("/students", (req, res) => {
res.json(students); });
app.delete("/students/:id", (req, res) => {
const id = req.params.id;
students = students.filter((s) => s.id !== id);
res.send(`Student with ID ${id} deleted`); });
app.listen(3000, () => {
console.log("Server started at http://localhost:3000");
});
Expected Output
1. POST → http://localhost:3000/students with body
2. { "id": "1", "name": "Baby" }
Response: Student added successfully!
3. GET → http://localhost:3000/students
Response: [{"id":"1","name":"Baby"}]
4. DELETE → http://localhost:3000/students/1
Response: Student with ID 1 deleted
1(c) Write a program to show the working of middleware.
const express = require("express");
const app = express();
const logger = (req, res, next) => {
console.log(`Request Method: ${req.method}, URL: ${req.url}`);
next(); // Pass to next function};
app.use(logger); // Applying middleware
app.get("/", (req, res) => {
res.send("Home Page");});
app.get("/about", (req, res) => {
res.send("About Page");
});
app.listen(3000, () => {
console.log("Server started at http://localhost:3000");
});
Expected Output (Console + Browser)
If you open http://localhost:3000/about:
Console Output:
Request Method: GET, URL: /about
Browser Output:
About Page
EXPERIMENT 2 -