🏠 Your Node.js Server: The Restaurant That Never Sleeps
Imagine you own a magical restaurant. People come to your door, ask for things, and you give them exactly what they need. That’s what an HTTP server does! It listens for visitors (requests) and serves them food (responses).
Today, we’ll build this restaurant together. Let’s go!
🎯 What We’ll Learn
- Handling GET requests – When guests ask “What’s on the menu?”
- Handling POST requests – When guests say “Here’s my order!”
- Parsing request body – Reading what guests wrote on their order slip
- Routing basics – Sending guests to the right table
- Serving static files – Handing out pre-made menus and photos
- Server timeout configuration – Not waiting forever for slow guests
- Creating HTTPS server – Locking the door with a secret key
1️⃣ Handling GET Requests
What is a GET Request?
Think of GET like a guest peeking through your window and asking: “Hey, can you show me your menu?”
They’re asking for information. They’re not giving you anything – just looking.
Simple Example
const http = require('http');
const server = http.createServer(
(req, res) => {
if (req.method === 'GET') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Welcome! Here is our menu!');
}
}
);
server.listen(3000);
console.log('Restaurant open on port 3000!');
🎨 Flow Diagram
graph TD A["Guest arrives"] --> B{What do they want?} B -->|GET| C["Show them the menu"] C --> D["Guest is happy!"]
Real-World Uses
- Loading a webpage
- Fetching user profiles
- Getting a list of products
2️⃣ Handling POST Requests
What is a POST Request?
POST is like a guest walking in and saying: “Here’s my order! I want pizza with extra cheese!”
They’re sending you something – data, information, their order.
Simple Example
const http = require('http');
const server = http.createServer(
(req, res) => {
if (req.method === 'POST') {
res.writeHead(201, {
'Content-Type': 'text/plain'
});
res.end('Got your order! Coming right up!');
}
}
);
server.listen(3000);
The Difference
| GET | POST |
|---|---|
| “Show me!” | “Take this!” |
| Asks for data | Sends data |
| Safe to repeat | Creates something new |
3️⃣ Parsing Request Body
The Problem
When guests send an order (POST), they write it on a slip of paper. But the paper arrives piece by piece – like a puzzle!
We need to collect all the pieces before reading.
How to Read the Order
const http = require('http');
const server = http.createServer(
(req, res) => {
if (req.method === 'POST') {
let body = '';
// Collect pieces
req.on('data', chunk => {
body += chunk.toString();
});
// All pieces collected!
req.on('end', () => {
const order = JSON.parse(body);
console.log('Order:', order);
res.end('Order received!');
});
}
}
);
server.listen(3000);
🎨 How Data Arrives
graph TD A["Guest sends order"] --> B["Piece 1 arrives"] B --> C["Piece 2 arrives"] C --> D["Piece 3 arrives"] D --> E["END signal"] E --> F["Now we can read it!"]
Why Pieces?
Big orders (like a file upload) are too heavy to carry at once. So they come in small chunks. Your server collects them like a puzzle!
4️⃣ Routing Basics
What is Routing?
Imagine your restaurant has different sections:
/pizza→ Pizza counter/drinks→ Drink bar/desserts→ Sweet corner
Routing is like having a host who guides each guest to the right place!
Simple Router
const http = require('http');
const server = http.createServer(
(req, res) => {
const url = req.url;
if (url === '/') {
res.end('Welcome to our restaurant!');
}
else if (url === '/pizza') {
res.end('🍕 Pizza section!');
}
else if (url === '/drinks') {
res.end('🥤 Drinks section!');
}
else {
res.writeHead(404);
res.end('Sorry, we do not have that!');
}
}
);
server.listen(3000);
🎨 Routing Flow
graph TD A["Guest asks for /pizza"] --> B{Check the path} B -->|/| C["Welcome page"] B -->|/pizza| D["Pizza section"] B -->|/drinks| E["Drinks section"] B -->|???| F["404 Not Found"]
5️⃣ Serving Static Files
What Are Static Files?
These are pre-made things that don’t change:
- HTML pages (your menu design)
- Images (food photos)
- CSS files (decorations)
- JavaScript files (interactive features)
Serving a File
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer(
(req, res) => {
// Build the file path
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './index.html';
}
// Read and send the file
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(404);
res.end('File not found!');
} else {
res.writeHead(200);
res.end(content);
}
});
}
);
server.listen(3000);
Common Static Files
| File Type | Purpose |
|---|---|
.html |
Page structure |
.css |
Page styling |
.js |
Page behavior |
.png/.jpg |
Images |
6️⃣ Server Timeout Configuration
The Problem
What if a guest stands at your counter for hours without ordering? You can’t wait forever!
Timeout tells your server: “If nothing happens in X seconds, move on.”
Setting Timeouts
const http = require('http');
const server = http.createServer(
(req, res) => {
res.end('Hello!');
}
);
// Wait max 30 seconds for a request
server.timeout = 30000;
// Wait max 5 seconds for headers
server.headersTimeout = 5000;
// Wait max 2 minutes between requests
server.keepAliveTimeout = 120000;
server.listen(3000);
console.log('Server ready with timeouts!');
Types of Timeouts
| Timeout | What It Controls |
|---|---|
timeout |
Total request time |
headersTimeout |
Time to receive headers |
keepAliveTimeout |
Time between requests |
Why Timeouts Matter
Without timeouts:
- Slow connections block your server
- Attackers can freeze your restaurant
- Resources get wasted
With timeouts:
- Your server stays healthy
- Bad connections get cleaned up
- Everyone gets served faster!
7️⃣ Creating HTTPS Server
What is HTTPS?
HTTP is like shouting your order across a crowded room. Everyone can hear!
HTTPS is like whispering your order in a secret code. Only you and the waiter understand!
The Secret Ingredients
You need two special files:
- Private Key – Your secret decoder ring
- Certificate – Your ID card that proves you’re legit
Creating an HTTPS Server
const https = require('https');
const fs = require('fs');
// Load your secret files
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem')
};
// Create secure server
const server = https.createServer(
options,
(req, res) => {
res.writeHead(200);
res.end('🔒 Secure connection!');
}
);
server.listen(443);
console.log('Secure restaurant open!');
🎨 HTTP vs HTTPS
graph TD A["Guest sends order"] --> B{HTTP or HTTPS?} B -->|HTTP| C["Order sent in plain text"] C --> D["Anyone can read it!"] B -->|HTTPS| E["Order is encrypted"] E --> F["Only server can read it!"]
Getting Real Certificates
For real websites, get certificates from:
- Let’s Encrypt (free!)
- Certificate authorities (paid)
For testing, create self-signed certificates.
🎉 Putting It All Together
Here’s a complete mini-server with everything we learned:
const http = require('http');
const fs = require('fs');
const server = http.createServer(
(req, res) => {
const { method, url } = req;
// Routing + Methods
if (method === 'GET' && url === '/') {
res.end('Welcome!');
}
else if (method === 'GET' && url === '/menu') {
// Serve static file
fs.readFile('./menu.html', (err, data) => {
if (err) {
res.writeHead(404);
res.end('Not found');
} else {
res.end(data);
}
});
}
else if (method === 'POST' && url === '/order') {
// Parse body
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
console.log('Order:', body);
res.end('Order received!');
});
}
else {
res.writeHead(404);
res.end('Not found');
}
}
);
// Set timeout
server.timeout = 30000;
server.listen(3000);
console.log('Full restaurant running!');
🌟 Key Takeaways
| Concept | Restaurant Analogy |
|---|---|
| GET | “Show me the menu” |
| POST | “Here’s my order” |
| Body parsing | Reading the order slip |
| Routing | Guiding guests to sections |
| Static files | Pre-printed menus |
| Timeouts | Don’t wait forever |
| HTTPS | Secret whisper code |
🚀 You Did It!
You now know how to:
- ✅ Handle GET requests (show information)
- ✅ Handle POST requests (receive information)
- ✅ Parse request bodies (read incoming data)
- ✅ Route requests (send to the right place)
- ✅ Serve static files (HTML, CSS, images)
- ✅ Set timeouts (keep your server healthy)
- ✅ Create HTTPS servers (secure connections)
Your Node.js restaurant is ready to serve the world! 🎉
