0% found this document useful (0 votes)
3 views16 pages

Node Module5 HTTPServer

This document outlines a module focused on creating an HTTP server from scratch using Node.js without Express. It covers topics such as understanding request and response objects, manual routing, handling different content types, and managing POST requests. The module emphasizes the importance of understanding the underlying HTTP protocol before moving on to Express for simplified server management.

Uploaded by

vischiragjain
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Node Module5 HTTPServer

This document outlines a module focused on creating an HTTP server from scratch using Node.js without Express. It covers topics such as understanding request and response objects, manual routing, handling different content types, and managing POST requests. The module emphasizes the importance of understanding the underlying HTTP protocol before moving on to Express for simplified server management.

Uploaded by

vischiragjain
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

M E R N S TA C K — N O D E .

J S F O U N D AT I O N

Module 5: HTTP Server From Scratch


Bina Express ke, sirf Node ke http module se, apna
pehla real web server banate hain.

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327


ROADMAP

Is Module Mein Kya Kya Cover Hoga

1 2
http module se pehla server banana req aur res objects samajhna

3 4
Manual routing — if/else se Alag-alag content types serve karna

5 6
POST requests handle karna Real-world JSON API + Express kyun banega

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 2


QUICK RECAP

Module 4 Se Yaad Hai?


• Promises, async/await, aur Event Loop samjha — Node non-blocking kaise rehta hai.
• Ab tak humne Node se sirf files padhi/likhi hain — kisi 'server' ki tarah kaam nahi kiya.
• Backend ka pura point hai — browser se requests receive karna, aur response bhejna.
• Aaj wahi seekhenge: Node ka built-in http module, jisके upar Express (agla topic) bana hai.

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 3


WHY BOTHER?

Bina Express Ke Kyun Seekhein?


Agla module Express hoga — jo ye sab kuch bahut aasan bana dega. Par pehle manually karna zaroori hai:

Samjhoge Express KYA Simplify Karta Hai

Jab dekhoge Express mein 3 lines mein kaam ho raha hai, pata hoga ye 3 lines asal mein kya kar rahi hain

HTTP Protocol Ki Real Samajh

Request/Response cycle — web ka fundamental building block — seedhe experience karoge

Debugging Better Hogi

Jab Express mein kuch error aayega, andar ka concept pata hoga isliye samajh aayega

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 4


SETUP

http Module — createServer()


Node ke saath built-in — koi install nahi chahiye.

const http = require('http')

const server = [Link]((req, res) => {


// har request yahan aati hai
[Link]("Namaste, duniya!")
})

// createServer() ek callback leta hai jo HAR


// incoming request pe automatically chalta hai

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 5


HANDS-ON

Tumhara Pehla Server — Poora Code

const http = require('http')

const server = [Link]((req, res) => {


[Link]("Namaste, duniya!")
})

[Link](3000, () => {
[Link]("Server chal raha hai: [Link]
})

Run karo: node [Link]

Ab browser mein localhost:3000 kholo — 'Namaste, duniya!' dikhega. Ye request kabhi khatam nahi hoti (jab tak Ctrl+C na dabao) — server hamesha 'sun' raha
hai.

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 6


REQ OBJECT

req — Browser Ne Kya Bheja?


req (request) mein wo saari jaankari hoti hai jo browser ne server ko bheji.

const server = [Link]((req, res) => {


[Link]([Link]) // '/students', '/about', etc.
[Link]([Link]) // 'GET', 'POST', 'PUT', 'DELETE'
[Link]([Link]) // content-type, user-agent, etc.

[Link]("Received!")
})

// Browser mein /students/5 kholo, terminal mein


// dekho [Link] = '/students/5' print hota hai

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 7


RES OBJECT

res — Server Wapas Kya Bhejega?


res (response) se hum status code, headers, aur asal content decide karte hain.

const server = [Link]((req, res) => {


[Link](200, { 'Content-Type': 'text/plain' })
[Link]("Sab theek hai!")
})

// 200 = status code ("OK")


// 404 = Not Found, 500 = Server Error, waise hi kai aur

// [Link]() ZAROORI hai — bina is के response kabhi


// khatam nahi hoga, browser hamesha 'loading' dikhayega

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 8


ROUTING

Manual Routing — if/else Se


Different URL, different response — abhi ke liye if/else se check karte hain.

const server = [Link]((req, res) => {


if ([Link] === '/' && [Link] === 'GET') {
[Link]("Home Page")
} else if ([Link] === '/students' && [Link] === 'GET') {
[Link]("Student List")
} else {
[Link](404)
[Link]("Page Not Found")
}
})

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 9


CONTENT TYPES

Text, JSON, Ya HTML — Kya Bhejein?


Content-Type header browser ko batata hai response ko KAISE samjhein.

// JSON bhejna (APIs ke liye sabse common)


if ([Link] === '/api/students') {
[Link](200, { 'Content-Type': 'application/json' })
[Link]([Link]([{ name: "Ananya" }]))
}

// HTML bhejna
if ([Link] === '/') {
[Link](200, { 'Content-Type': 'text/html' })
[Link]("<h1>Namaste!</h1>")
}

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 10


POST REQUESTS

POST Body Padhna — Thoda Tricky


GET jaisa seedha nahi hai — POST ka data 'chunks' mein, stream ki tarah aata hai, ek saath nahi.

if ([Link] === '/students' && [Link] === 'POST') {


let body = ''

[Link]('data', (chunk) => {


body += chunk // data tukdo mein aata hai
})

[Link]('end', () => {
const newStudent = [Link](body)
[Link]("Naya student:", newStudent)
[Link]("Received!")
})
}

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 11


PUT IT TOGETHER

Real Example — Students JSON API


Module 3 ka fs + aaj ka http — GET aur POST dono, ek chhote API mein.

const http = require('http')


const { getAll, addStudent } = require('./studentStore')

const server = [Link]((req, res) => {


[Link]('Content-Type', 'application/json')

if ([Link] === '/students' && [Link] === 'GET') {


[Link]([Link](getAll()))
} else if ([Link] === '/students' && [Link] === 'POST') {
/* [Link]('data'/'end') se body padho, addStudent() */
}
})

[Link](3000)

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 12


COMING UP

Isमें Kya Dikkat Hai? (Express Kyun Banega)

Socho 20 alag routes ho — GET/POST/PUT/DELETE, sab manually if/else se. Dekho kya dikkat aayegi:

• if/else ki ek lambi, mushkil-se-padhi-jaane-wali chain ban jaayegi

• Dynamic routes (/students/:id jaisa) manually parse karna painful hai

• Har baar POST body padhne ka wahi stream-wala code repeat karna padega

• Error handling, middleware, static files — sab kuch khud likhna padega

Isliye [Link] banaya gaya — yehi sab kuch chhota, clean syntax mein. Agla module is के saath hi shuru hoga!

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 13


WATCH OUT

Common HTTP Server Mistakes


[Link]() call karna bhool jaana

Fix: bina isके response kabhi complete nahi hota, browser hamesha load karta rahega


Content-Type set na karna

Fix: browser/client ko pata nahi chalega response JSON hai ya text — hamesha batao


POST body ko synchronously padhne ki koshish karna

Fix: body stream mein aata hai — [Link]('data') aur 'end' ka wait karo


Port already in use error ignore karna

Fix: purana server band karo (Ctrl+C), ya alag port try karo

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 14


WRAP UP

Quick Recap + Practice Task


• [Link]((req, res) => {...}) — server ka core
• [Link], [Link] — request ke baare mein jaankari 🎯 PRACTICE TASK
• [Link](), [Link]() — response bhejna
• [Link](PORT) — server ko chalu karna
• Manual routing = if/else on [Link] + [Link] 1. Apna pehla server banao — port 3000 pe 'Namaste!' bhejo
• POST body [Link]('data'/'end') se stream mein aata hai
2. 3 routes banao: '/', '/about', aur ek 404 wala else

3. Ek route JSON return kare, ek route HTML return kare

4. Bonus: ek POST route banao jo body padh ke terminal mein


print kare

Next → Hands-On Lab: Notes API

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 15


Shukriya!
Questions? Doubts? Comment ya class mein poocho.
Agla hai poore phase ka Hands-On Lab — Notes API banate hain!

YC OT E S C O M P U T E R C L A S S E S

You might also like