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