const express = require("express"); const app = express(); // middleware app.use((req, res, next) => { console.log("Middleware chal gaya"); next(); // next middleware / route ko bhejta hai }); app.get("/", (req, res) => { res.send("Hello World"); }); app.listen(3000); πŸ“Œ Types of Middleware 1️⃣ Application level app.use(myMiddleware) 2️ Route level app.get("/admin", myMiddleware, (req,res)=>{ res.send("Admin page"); }); 3️⃣ Built-in Jaise: app.use(express.json()); Error middleware app.use((err, req, res, next) => { res.send("Error aaya"); }); πŸ‘‰ app.use(express.json()) kya karta hai? Ye line Express ko bolti hai: β€œAgar koi request JSON format me aaye, to usko read karke JavaScript object bana do aur req.body me daal do.” Maan lo Postman ya frontend se tum ye bhejte ho: { "name": "Rahul", "age": 22 } Agar tumne likha hai: app.use(express.json()); to Express automatically: βœ… JSON ko parse karega βœ… JS object banayega βœ… req.body me daal dega Phir tum controller me likh sakte ho: app.post("/user", (req, res) => { console.log(req.body); }); Output: { name: "Rahul", age: 22 } Agar express.json() NA likho? To: ❌ req.body = undefined kyonki Express ko pata hi nahi ki JSON kaise read karna hai. One-line me: πŸ‘‰ app.use(express.json()) = JSON translator πŸ‘‰ express.urlencoded() kya karta hai? Ye middleware HTML form se aane wala data read karta hai aur usko bhi req.body me daal deta hai. Matlab: Real example (HTML form):
Browser actually backend ko aise bhejta hai: email=test@gmail.com&password=123456 ⚠️ Ye JSON nahi hota β€” isko bolte hain URL encoded data. Ab ye line ka magic: app.use(express.urlencoded({ extended: true })); Express ko bol rahe ho: πŸ‘‰ β€œIs type ke encoded form data ko samajh ke req.body me daal do.” Phir route me: app.post("/login", (req, res) => { console.log(req.body); }); Output: { email: "test@gmail.com", password: "123456" } ❓ { extended: true } ka matlab? Simple version: βœ… extended: true Nested / complex objects allow karta hai: Becomes: { user: { name: "Rahul", age: "22" } } πŸ‘‰ express.static() kya karta hai? Ye Express ko bolta hai: β€œIs folder ke andar jo files hain (CSS, images, JS, etc.), unko directly browser ko de dena.” Matlab frontend assets serve karta hai. Example: app.use(express.static("public")); Iska matlab: πŸ‘‰ public folder ko publicly accessible bana diya. project/ β”‚ β”œβ”€ app.js └─ public/ β”œβ”€ style.css β”œβ”€ logo.png └─ main.js Ab browser me directly access kar sakte ho: CSS: http://localhost:3000/style.css Image: http://localhost:3000/logo.png Short recap: express.json() β†’ JSON read express.urlencoded() β†’ Form data read express.static() β†’ CSS / images / JS serve