Hirenix kaise padhata hai
Ek chapter. 90 minute.
Interview ke liye taiyaar.
Har concept ek real-world problem se — jaisa production code mein aata hai, waisa. Ratna nahi padta, samajh aa jaata hai. Har question ka model answer diya hai: interviewer ko exactly kya bolna hai, aur kyun. Phir usi chapter ka AI mock interview.
- 📖Concept, 5 min meinJargon nahi — seedhi baat
- 🛠️Real-world problemJaisa production code mein aata hai
- 💬Model answerInterview mein kya bolna hai
- 🧠FlashcardsRevision 10 min mein
- 🤖AI mock interviewFollow-up bhi poochta hai
- 📊Weak topicsKahan phans rahe ho, pata chale

Farq content ka nahi, filter ka hai — sirf wahi jo production mein actually use hota hai aur interview mein actually poocha jaata hai. Kitaabi topics jo industry mein kahin nahi chalte, wo yahan nahi milenge.
What you’ll learn
- ●Express kya hai?
- ●Express vs raw http
- RoutingFree account
- Middleware (the core)Free account
- Request & ResponseFree account
- Body parsingFree account
- Route params & queryFree account
- Router (modular routes)Free account
- Error-handling middlewareFree account
- Serving static filesFree account
- CORSFree account
- JWT auth middlewareFree account
- Request validationFree account
- REST API designFree account
- HTTP status codesFree account
- Interview recapFree account
- ●Project 1: CRUD REST API
- Project 2: JWT auth APIFree account
- Project 3: Middleware pipelineFree account
Express kya hai?
Socho tum ek chai ki tapri kholna chahte ho. Tum chaho to sab kuch zero se bana sakte ho — apni lakdi khud kaato, apna chulha khud banao, paani ke liye khud kuan khodo. Kaam ho jaayega, par saara din plumbing me nikal jaayega, chai banane me nahi. Ya phir tum ek ready-made stall kit kiraye par le lo: chulha, counter, paani ka nal, menu board sab set. Ab tum sirf customers ko serve karne par focus karo. Express wahi ready-made kit hai.
Express me, raw kaam Node ke http module ka hai — yaad hai Node ka project-http-server, jahan tumne if (req.url === '/health' && req.method === 'GET') haath se likha, headers khud set kiye, aur har response ko JSON.stringify kiya? Wo "apna chulha khud banao" wala version hai. Express ek chhota web framework hai jo usi same http server ke upar baithta hai aur tumhe conveniences deta hai: saaf routing (app.get('/users', ...)), request/response helpers (res.json(...)), aur middleware — taaki tum bahut kam boilerplate likho. Tum shuru karte ho const app = express() se, routes register karte ho app.get(path, handler) jaise, aur darwaza kholte ho app.listen(port) se. Andar se Express abhi bhi http.createServer hi call kar raha hai — wo Node ko replace nahi karta, use wrap karta hai.
🌍 Real-world example: Raw http me sirf
GET /healthko JSON dene ke liye ~8 lines lagti thi — manualwriteHead, manualContent-Type, manualstringify. Express me ye ek line hai:app.get('/health', (req, res) => res.json({ status: 'ok' })).res.jsonJSON header bhi set karta hai AUR stringify bhi kar deta hai. Is bachat ko 30 routes par multiply karo aur samajh aayega har MERN backend Express kyun use karta hai.
💡 web framework = ek library jo server banane ke liye ready structure (routing, middleware, helpers) deti hai, taaki tum low-level plumbing ki jagah app logic likho.
💡 unopinionated = Express tum par koi folder layout ya database force nahi karta — tum app ko jaise chaho waise arrange karo (opinionated framework ka ulta).
💡 middleware = ek function jo har request par arrival aur response ke beech chalta hai — logging, auth, body parsing waghairah ke liye.
Ye fit kahan hota hai? Express MERN ka "E" hai (MongoDB, Express, React, Node). React wo frontend hai jo user dekhta hai; Express API / backend layer hai — ye React se requests leta hai, database se baat karta hai, aur JSON wapas bhejta hai. Node wo runtime hai jispar ye sab chalta hai. To jab interviewer pooche "Express kya hai aur sirf http kyun na use karein?", jawab hai: ye Node ke http ke upar ek minimal framework hai jo routing, middleware, aur req/res helpers add karta hai taaki tum kam boilerplate me tezi se APIs banao.
Standard definition: Express is a minimal, unopinionated web framework for Node.js built on top of the built-in http module, adding routing, middleware, and request/response helpers so you can build servers and APIs with far less boilerplate than raw http.
const express = require('express');
const app = express();
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(3000, () => console.log('Server on 3000'));Express vs raw http
Socho tumhe ek car chahiye. Option one: raw parts khareedo — engine, wheels, chassis, wiring — aur khud jod ke banao. Kaam ho jaata hai, par har nut-bolt haath se lagana padta hai aur kuch bhoolna aasaan hai. Option two: ek ready-made car khareedo jisme steering, brakes, aur dashboard pehle se wired hain — bas chalao. Yahi farq hai Node ke raw http module aur Express ke beech me.
Express me, tumhe abhi bhi ek HTTP server milta hai — par boilerplate tumhare liye ho chuka hota hai. Jahan raw http ek bada handler deta hai aur tum req.url/req.method par khud branch karte ho, wahan Express deta hai asli routing (app.get('/users', ...), app.post(...)), req/res helpers (res.json(obj) ek hi call me JSON header set karta hai AUR stringify karta hai — koi manual writeHead + JSON.stringify nahi), middleware (request pipeline me reusable functions), aur built-in body parsing (express.json() req.body bhar deta hai). Same server, code ka ek chhota sa hissa.
🌍 Real-world example: Ek
GET /healthjo{"status":"ok"}return karta hai. Raw http me tumreq.url === '/health'check karte ho,res.writeHead(200, {'Content-Type':'application/json'}), phirres.end(JSON.stringify({status:'ok'}))— teen soch-samajh ke steps. Express me ye ek line hai:app.get('/health', (req, res) => res.json({ status: 'ok' })). http me doosra route add karo to aurif/elsestack hota jaata hai; Express me bas ek aurapp.getadd karo.
💡 routing = incoming request ke URL + HTTP method ko sahi handler function se match karna.
💡 middleware = ek function
(req, res, next)jo request→response cycle ke dauran chalta hai (logging, auth, parsing) tumhare handler se pehle.
💡 body parsing = request body ke raw bytes ko padh kar unhe ek usable
req.bodyobject me badalna.
Key point — Express andar se Node ka http hi hai, uska replacement nahi. app.listen(3000) andar se http.createServer(app) call karta hai aur tumhare app ko wahi http server ko de deta hai. req aur res wahi objects hain jo http module deta hai, bas extra helpers jaise res.json aur req.params ke saath sajaye hue. To Express koi naya server ya nayi language nahi hai — ye ek patli, convenient layer hai us same http module ke upar jo tum pehle seekh chuke ho. Raw version jaanne ka matlab hai tumhe pata hai Express tumhare liye kya kar raha hai.
Standard definition: Express is a minimal, unopinionated web framework that runs on top of Node's built-in http module, adding routing, middleware, and request/response helpers (like res.json and req.body) so you write far less boilerplate than raw http.createServer — but it still uses Node's http server underneath, not a replacement for it.
// ---------- RAW HTTP (mushkil tareeka) ----------
const http = require('http');
const users = [{ id: 1, name: 'Asha' }];
http.createServer((req, res) => {
if (req.url === '/users' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(users)); // stringify + header khud lagao
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
}).listen(3000, () => console.log('Server on 3000'));
// ---------- EXPRESS (same server, kam code) ----------
const express = require('express');
const app = express();
app.use(express.json()); // built-in body parsing -> req.body
app.get('/users', (req, res) => res.json(users)); // routing + res.json
app.post('/users', (req, res) => {
const user = { id: users.length + 1, name: req.body.name };
users.push(user);
res.status(201).json(user); // status + json chained
});
app.listen(3000, () => console.log('Server on 3000')); // andar se http.createServer use karta haiProject 1: CRUD REST API
Kya bana rahe hain: Ek poora CRUD REST API ek /todos resource ke liye Express ke saath — saare list karo, ek nikalo, banao, update karo, delete karo. Data ek simple in-memory array mein rehta hai (asli database natural next step hai, ant mein note kiya). Ye ek backend fresher ke liye THE resume project hai: ye express.json() body parsing + 5 CRUD routes + req.params/req.body + sahi status codes + ek 404 handler ko ek saath jodta hai — wahi skeleton jo har backend job tumse interview mein banwana chahti hai.
Ant tak tum ek request ko seedha trace kar paoge: request aati hai → Express route match karta hai → handler req.params/req.body padhta hai → hum array mutate karte hain → res.status(code).json(...) reply karta hai. Agar tumne Node ka project-file-todo-api (raw http version) kiya hai, to dekho kaise Express wo saari plumbing hata deta hai jo tumne haath se likhi thi.
🌍 Real-world example: Ye bilkul wahi hai jo ek to-do app ka backend karta hai. Frontend
POST /todosbhejta hai{"title":"buy milk"}ke saath, server use banakar201 Createdke saath naya todo (uskiidsamet) reply karta hai. Baad meinGET /todosbhejta hai list dikhane ke liye. Array ko Mongo/Postgres call se badal do aur ye production hai.
💡 CRUD = Create, Read, Update, Delete — chaar cheezein jo tum kisi bhi resource ke saath karte ho. REST mein ye
/todosjaise noun URL pe POST, GET, PUT/PATCH, DELETE se map hoti hain.
💡 REST API = data ke saath kaam karne ke liye URL + HTTP-method rules ka set. Method verb hai (GET read, POST create…), URL noun hai (
/todos,/todos/3).
Step 0 — Mental model (pehle ye padho)
Raw Node mein tumne ek bada handler likha tha aur req.method + req.url ko if ki deewar se match kiya, :id ke liye URL khud split kiya, aur body ko stream chunks mein collect kiya. Express teeno ko replace karta hai:
- Routing —
app.get('/todos', handler),app.post('/todos', handler). Koi method/urlifnahi. Express verb + path match karke sahi function call karta hai. - Route params — path mein
:id(/todos/:id) parsed hokarreq.params.idpe aata hai. Koiurl.split('/')nahi. - Body parsing —
app.use(express.json())JSON body tumhare liye padhta hai aurreq.bodyde deta hai. Koireq.on('data')chunk-collecting nahi.
Aur replies chhote ho jaate hain: res.status(201).json(obj) ek chainable line mein status set karke JSON bhejta hai. Wahi REST concepts, code ka ek chhota hissa.
Step 1 — App + express.json()
Har Express app inhi teen lines se shuru hota hai:
const express = require('express');
const app = express();
app.use(express.json()); // JSON bodies ko req.body mein parse karo
Ho ye raha hai:
express()app banata hai — ek object jo khud bhi wo request handler hai jise Node ka http server call karega. (Hood ke neecheapp.listenabhi bhihttp.createServeruse karta hai — Express usihttpmodule ke upar baithta hai jo tumne seekha.)app.use(express.json())ek middleware register karta hai jo har request pe tumhare routes se pehle chalta hai. YeContent-Type: application/jsonwali requests dekhta hai, body padhta hai,JSON.parsekarta hai, aurreq.bodyset karta hai. Is line ke bina,req.bodyundefinedhota hai — sabse common Express gotcha.- Order matters:
express.json()un routes se upar register hona chahiye joreq.bodypadhte hain, kyunki middleware top-to-bottom chalta hai.
💡 Middleware = ek function jo request→response cycle ke dauraan chalta hai, tumhare route handler se pehle (ya uski jagah).
express.json()ek built-in hai; tum apna(req, res, next) => {}bhi likh sakte ho.
Step 2 — Hamara data + 5 CRUD routes
Hum todos ko ek normal array aur ek id counter mein rakhte hain — koi file nahi, koi DB nahi (abhi):
let todos = [];
let nextId = 1;
Ab paanch routes. Har ek ek HTTP verb ko ek CRUD action se map karta hai:
// READ all
app.get('/todos', (req, res) => {
res.status(200).json(todos);
});
// READ one
app.get('/todos/:id', (req, res) => {
const id = Number(req.params.id);
const todo = todos.find(t => t.id === id);
if (!todo) return res.status(404).json({ error: 'Todo not found' });
res.status(200).json(todo);
});
// CREATE
app.post('/todos', (req, res) => {
const { title } = req.body;
if (!title) return res.status(400).json({ error: 'title is required' });
const todo = { id: nextId++, title, done: false };
todos.push(todo);
res.status(201).json(todo);
});
// UPDATE
app.put('/todos/:id', (req, res) => {
const id = Number(req.params.id);
const todo = todos.find(t => t.id === id);
if (!todo) return res.status(404).json({ error: 'Todo not found' });
if (req.body.title !== undefined) todo.title = req.body.title;
if (req.body.done !== undefined) todo.done = req.body.done;
res.status(200).json(todo);
});
// DELETE
app.delete('/todos/:id', (req, res) => {
const id = Number(req.params.id);
const before = todos.length;
todos = todos.filter(t => t.id !== id);
if (todos.length === before) return res.status(404).json({ error: 'Todo not found' });
res.status(204).end();
});
Ho ye raha hai — poora CRUD table ek nazar mein:
- GET
/todos→ list padho →200 OKarray ke saath. - GET
/todos/:id→req.params.idid deta hai →findkaro →200todo ke saath, ya404agar wahan nahi. - POST
/todos→req.body.titlepadho → validate → create →201 Created("maine naya resource banaya" wala code). - PUT
/todos/:id→ find + di gayi fields update karo →200, ya404. - DELETE
/todos/:id→ hatao →204 No Content(success, wapas bhejne ko kuch nahi), ya404.
Dhyaan do: koi url.split nahi, koi req.on('data') nahi, koi manual Content-Type header nahi. Express ne humein req.params.id, req.body, aur res.json() diye.
💡
res.status(code).json(obj)chainable hai —status()resreturn karta hai, to tum code set karke body ek line mein bhejte ho.res.json()khudContent-Type: application/jsonbhi set kar deta hai.
💡 204 No Content DELETE ke liye: operation safal hua par wapas bhejne ko kuch meaningful nahi, to hum
.end()se empty body bhejte hain,.json()se nahi.
Step 3 — Ek POST ko end to end TRACE karo (body → validate → create → 201)
Ye interview ka money-shot hai. Har beat follow karo — client POST /todos bhejta hai {"title":"buy milk"} ke saath:
- Middleware pehle chalta hai →
express.json()Content-Type: application/jsondekhta hai, body stream padhta hai,JSON.parsekarta hai, aurreq.body = { title: 'buy milk' }set karta hai. Phirnext()call karke control router ko de deta hai. - Route match → Express
POST+/todosdekhta hai aurapp.post('/todos', ...)handler call karta hai. (Koiif (method === 'POST' && url === '/todos')nahi — framework ne match kiya.) - Body padho →
const { title } = req.body'buy milk'nikalta hai. Ye sirf isliye kaam karta hai kyunki step 1 meinexpress.json()chala — wo middleware hata do aurreq.bodyundefinedho jaata hai aur ye throw karega. - Validate →
titlenahi?return res.status(400).json({ error: 'title is required' })aur ruko. (Client ne galat data bheja → 400.)returnzaroori hai — ye handler rok deta hai taaki hum 201 bhi na bhej dein. - Create →
{ id: 1, title: 'buy milk', done: false }banao (idnextId++se, jo1hai phir2ban jaati hai) aurtodosmeinpushkaro. - Reply →
res.status(201).json(todo)— status201 Created, body naya todo uski id ke saath. Client ab wo id jaanta hai jise wo aage GET/PUT/DELETE ke liye use kar sakta hai.
Read-back se saabit karo: client GET /todos bhejta hai. Wo handler res.status(200).json(todos) chalata hai → array mein ab [{ id: 1, title: 'buy milk', done: false }] hai → return. (In-memory ka matlab restart pe gayab — yahi ek cheez asli DB theek karta hai, aur isi liye Step 5 wahan ishaara karta hai.)
💡 Raw Node se contrast:
httpversion mein isi POST ke liye ek haath se likhaparseBody(req)chahiye tha joreq.on('data')chunks collect karke'end'peJSON.parsekarta, plus ek manualif (method === 'POST' && url === '/todos'). Express ne dono muft mein kar diye — yahi framework ka poora point hai.
Step 4 — Ek GET /:id ko end to end TRACE karo (param → find → 200 ya 404)
Client GET /todos/1 bhejta hai:
- Route match → Express
GETko pattern/todos/:idke against match karta hai.:idsegment ek route param hai; Express path se1parse karkereq.params = { id: '1' }set karta hai. - Param padho →
const id = Number(req.params.id). Route params hamesha strings hote hain ('1'), to hum useNumber()se1banate hain taaki numerictodo.idse compare kar sakein. (Isi wajah se query values bhi strings hoti hain.) - Find →
todos.find(t => t.id === id)us todo ko dhoondta hai jiski id match kare. - Result pe branch:
- Mila →
res.status(200).json(todo)→200 OKus single todo ke saath. - Nahi mila →
return res.status(404).json({ error: 'Todo not found' })→404, kyunki id exist nahi karti.returnhumein neeche gir kar doosra response bhejne se rokta hai (resdo baar call karna "Cannot set headers after they are sent" throw karta hai — ek aur classic gotcha).
- Mila →
Raw Node se compare karo: wahan tum Number(url.split('/')[2]) karke id ko /todos/1 se nikaalte the. Express ne use req.params.id ke roop mein route path ke :id se de diya. Router URL parsing karta hai.
Step 5 — 404 handler + DB ka note
Agar client kisi aise route pe jaaye jo humne kabhi define hi nahi kiya, jaise GET /users? Ek catch-all sabse neeche add karo, saare asli routes ke baad:
// 404 — koi route match nahi hua
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
app.listen(3000, () => console.log('API on http://localhost:3000'));
Ho ye raha hai: middleware top-to-bottom chalta hai. Agar ek request upar ke paanch routes mein se kisi se match na kare, to wo is aakhri app.use(...) tak gir jaati hai, jo 404 reply karta hai. Isme koi path na hone se ye jo bhi yahan tak pahuncha us sab se match karta hai — isliye ise sabse aakhir mein register hona chahiye, warna ye asli routes ke liye bani requests ko nigal jaayega (middleware-order gotcha).
DB next step: abhi let todos = [] memory mein rehta hai, to har restart data mita deta hai (aur ye ek server process se aage scale nahi karta). Natural upgrade array ko database se badalna hai: todos.find(...) Todo.findById(id) (Mongoose/MongoDB) ya ek SELECT ... WHERE id = $1 (Postgres) ban jaata hai. Har route ka shape bilkul same rehta hai — handler, status codes, aur req.params/req.body badalte nahi; sirf data-access line badalti hai. Isi liye ye array version ek bilkul honest resume project hai: ye asli structure hai, bas ek swap kam.
🔎 Poora flow (wiring ka recap)
Har route wahi teen-beat wala gaana hai, ab Express-short:
- Match — Express verb + path ko tumhare handler pe route karta hai (
app.get/post/put/delete). Koi manualifnahi. - Read + change —
req.params.id(kaunsa resource) aurreq.body(naya data,express.json()ki wajah se); array mutate karo (find/push/filter). - Reply —
res.status(code).json(...)sahi code ke saath:200read/update,201create,204delete,400bad input,404not found.
🚀 Raw Node se Express tak — kya gayab hua
Raw http version |
Express version |
|---|---|
if (method === 'GET' && url === '/todos') |
app.get('/todos', ...) |
Number(url.split('/')[2]) |
req.params.id |
haath se likha parseBody(req) (stream chunks) |
app.use(express.json()) → req.body |
res.writeHead(201); res.end(JSON.stringify(x)) |
res.status(201).json(x) |
har reply pe res.setHeader('Content-Type', ...) |
res.json() khud set kar deta hai |
Wahi REST verbs, wahi status codes, wahi data logic — Express ne bas boilerplate delete kiya. Isi liye humne pehle mushkil tarike se banaya: ab tum theek se jaante ho ki Express hood ke neeche kya kar raha hai.
✅ Jo tumne abhi seekha
- Express mein ek poora CRUD REST API —
app.get/post/put/deletejo paanch verbs ko/todospe Create/Read/Update/Delete se map karte hain. express.json()— built-in middleware joreq.bodybharta hai; iske binareq.bodyundefinedhota hai.req.paramsvsreq.body— URL path se id (:id) vs JSON payload; params strings hote hain, to unheNumber()karo.- Sahi status codes —
200read/update,201create,204delete,400bad input,404not found. - Ek 404 catch-all jo sabse aakhir mein register hota hai taaki sirf sach mein unmatched routes pakde.
return res...ki aadat taaki tum kabhi do responses na bhejo ("headers already sent").- Raw Node ka bridge — Express routing + body-parsing boilerplate hatata hai; DB swap next step hai.
const express = require('express');
const app = express();
app.use(express.json()); // JSON bodies ko req.body mein parse karo
let todos = [];
let nextId = 1;
// READ all
app.get('/todos', (req, res) => {
res.status(200).json(todos);
});
// READ one
app.get('/todos/:id', (req, res) => {
const id = Number(req.params.id);
const todo = todos.find(t => t.id === id);
if (!todo) return res.status(404).json({ error: 'Todo not found' });
res.status(200).json(todo);
});
// CREATE
app.post('/todos', (req, res) => {
const { title } = req.body;
if (!title) return res.status(400).json({ error: 'title is required' });
const todo = { id: nextId++, title, done: false };
todos.push(todo);
res.status(201).json(todo);
});
// UPDATE
app.put('/todos/:id', (req, res) => {
const id = Number(req.params.id);
const todo = todos.find(t => t.id === id);
if (!todo) return res.status(404).json({ error: 'Todo not found' });
if (req.body.title !== undefined) todo.title = req.body.title;
if (req.body.done !== undefined) todo.done = req.body.done;
res.status(200).json(todo);
});
// DELETE
app.delete('/todos/:id', (req, res) => {
const id = Number(req.params.id);
const before = todos.length;
todos = todos.filter(t => t.id !== id);
if (todos.length === before) return res.status(404).json({ error: 'Todo not found' });
res.status(204).end();
});
// 404 — koi route match nahi hua (LAST register karo)
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
app.listen(3000, () => console.log('API on http://localhost:3000'));Express.jsinterview questions & answers
10 sample questions below — 163+ in the full bank inside.
Express me error-handling middleware kya hota hai?
Ye ek special middleware hai jiska signature char-argument wala hota hai (err, req, res, next). Jab bhi tum next(err) call karte ho, Express error ko yahi bhej deta hai, isliye har route me try/catch dohrane ke bajaye saare errors ek central jagah handle hote hain aur ek clean response jata hai.
In simple terms: Factory conveyor belt socho: normal middleware wo workers hain jo item aage badhate hain, aur error handler sabse end me reject bin hai jahan koi kharab item gir jata hai. Example: app.use((err, req, res, next) => res.status(500).json({ error: err.message })); app ka har next(err) yahi aa girega.
Express ko kaise pata chalta hai ki koi middleware error handler hai?
Sirf parameters ki ginti se — agar function me exactly char parameters hain (err, req, res, next), to Express usse error-handling middleware maan leta hai. err hata do to wo normal teen-arg middleware ban jata hai, isliye ye ginti optional nahi hai.
In simple terms: Ye ek aise form jaisa hai jisme ek mandatory 'complaint' box ho: jis form me wo extra box hai wo complaints desk jata hai, jisme nahi hai wo normal counter. Example: (err, req, res, next) => {} error handler hai; (req, res, next) => {} normal — body same, desk alag.
Same-origin policy kya hai?
Same-origin policy ek browser security rule hai jo ek web page ko rokta hai ki wo apne se alag origin par ki gayi requests ke responses ko padhe. Origin = protocol + domain + port ka combination; in teeno me se koi bhi alag ho to origin alag hai. Ye users ko protect karne ke liye hai taaki koi malicious site chupke se kisi doosri logged-in site ka data na padh le.
In simple terms: Origins ko building ke alag-alag flats samjho — tum kisi bhi darwaze par knock kar sakte ho, par andar ghus ke kisi aur ki daak nahi padh sakte. Browser deewaron ko enforce karta hai. Example: `http://site.com` aur `https://site.com` alag origins hain (protocol alag), aur `site.com:3000` aur `site.com:5000` bhi alag hain (port alag).
express.json() aur express.urlencoded() me kya farq hai?
Dono built-in body parsers hain, par alag Content-Types handle karte hain. express.json() application/json bodies parse karta hai; express.urlencoded() application/x-www-form-urlencoded (HTML form) bodies parse karta hai. Apps aksar dono register karte hain taaki dono formats accept ho.
In simple terms: Kaam same (req.body bharna), par input format alag — jaise do charger rakhna, ek USB-C aur ek micro-USB, do tarah ke phones ke liye. Jaise app.use(express.json()); app.use(express.urlencoded({ extended: true })); ab server JSON API calls aur simple form submits dono samajhta hai.
express.json() kya karta hai?
express.json() ek built-in middleware hai jo aane wali request body ko padhta hai, aur agar uska Content-Type application/json hai to JSON text ko JavaScript object me parse karke req.body pe daal deta hai. Ise ek baar app.use(express.json()) se register karte ho.
In simple terms: Ye ek translator hai jo wire pe aane wale JSON text ko real JS object me badal deta hai jise tum use kar sako. Text andar aata hai, object req.body pe chala jaata hai. Jaise app.use(express.json()); phir handler me req.body parsed object hota hai jaise { email: 'a@b.com' }, undefined ki jagah.
Express app me CORS kaise enable karte ho?
`cors` package install karo aur use middleware ki tarah `app.use(cors())` se apne routes se pehle register karo. Ye automatically Access-Control-Allow-Origin (aur related) headers responses me add kar deta hai. Tum `cors({ origin: 'http://localhost:3000' })` jaise options pass karke sabko allow karne ki jagah ek specific origin whitelist kar sakte ho.
In simple terms: cors middleware ek doorman rakhne jaisa hai jo har response par sahi 'allowed' sticker laga deta hai taaki browser use jaane de. Example: ```js const cors = require('cors'); app.use(cors({ origin: 'http://localhost:3000' })); ``` Ab React app :3000 se aane wali requests allowed hain.
express.json() ki jagah express.urlencoded() kab use karoge?
express.urlencoded() un bodies ko parse karta hai jo application/x-www-form-urlencoded format me aati hain — yani classic HTML <form> jo submit karta hai. Traditional form posts ke liye ise use karo; jab client JSON bheje (jaise fetch/axios JSON body ke saath) tab express.json() use karo.
In simple terms: Simple HTML form JSON nahi bhejta — woh data aise bhejta hai name=Ali&age=22 (key=value pairs & se jude hue). express.urlencoded() us string ko wapas req.body me decode karta hai. Jaise app.use(express.urlencoded({ extended: true })) name=Ali&age=22 ko req.body = { name: 'Ali', age: '22' } bana deta hai.
Tum POST request bhejte ho JSON body ke saath, lekin req.body undefined aata hai. Kyun?
Express request body ko automatically parse nahi karta. Body-parsing middleware ke bina req.body undefined hi rehta hai. app.use(express.json()) ko routes se pehle lagane par aane wali JSON req.body me parse ho jaati hai.
In simple terms: Request body raw bytes ki stream ban ke aati hai; jab tak tum bolo nahi, Express use usable object me convert nahi karta. Ise ek band courier parcel samjho — postman darwaze pe chhod deta hai par kholta nahi; express.json() woh banda hai jo use kholke andar ka saamaan tumhe deta hai. Jaise app.use(express.json()) ke baad, {"name":"Ali"} wali POST me req.body.name === 'Ali' milta hai.
CORS kya hai?
CORS (Cross-Origin Resource Sharing) ek browser ka mechanism hai jo server ko allow karta hai ki wo alag origin (alag protocol, domain, ya port) se aane wali requests ko explicitly permit kare. Default me browser same-origin policy ki wajah se cross-origin requests block karta hai; CORS wo controlled tareeka hai jisme server Access-Control-Allow-Origin headers bhejta hai.
In simple terms: Isko party ki guest list samjho: tumhara API party hai, aur default me sirf same ghar (same origin) ke guests andar aate hain. CORS host ka doosre addresses ko guest list me add karna hai. Example: API http://localhost:5000 par `Access-Control-Allow-Origin: http://localhost:3000` bhej ke React app ko :3000 se andar aane deta hai.
Error-handling middleware ko file me kahan register karna chahiye?
Isse SABSE LAST me register karna chahiye — saare routes aur baaki app.use() calls ke baad. Middleware upar-se-neeche chalta hai, isliye error handler ko pipeline ke bilkul end me hona padta hai taaki upar se aane wale errors ko pakad sake.
In simple terms: Trapeze ke neeche safety net jaisa: wo tabhi kaam karta hai jab acrobats ke neeche lagaya jaye, upar nahi. Example: pehle app.get('/users', ...) likho, aur app.use((err, req, res, next) => {...}) ko sabse aakhri app.use rakho — warna uske baad wale routes kabhi ispe nahi pahunchenge.
153+ more Express.js questions inside
Create a free account to read the full question bank, learn every topic, and practise with an AI mock interview.
Unlock all questions — freeReady to practise Express.js?
Unlock every topic free, then face an AI interviewer that asks follow-ups and grades your answers.