🏠The Post Office of the Internet: HTTP Server Fundamentals
Imagine you run a magical post office. Letters arrive, you read them, and you send back the perfect response. That’s exactly what an HTTP server does!
📬 What’s an HTTP Server?
Think of the internet like a giant neighborhood. Your HTTP server is like a helpful post office worker who:
- Listens for letters (requests) at a specific address
- Reads what people want
- Writes back with exactly what they need
Every website you visit has a post office worker (server) waiting to help you!
đź§° The http Module: Your Post Office Toolkit
Node.js gives you a special toolkit called the http module. It has everything you need to build your post office.
// Open your toolkit!
const http = require('http');
That’s it! One line, and you have superpowers. 🦸
What’s Inside the Toolkit?
| Tool | What It Does |
|---|---|
createServer() |
Builds your post office |
request |
The incoming letter |
response |
Your reply letter |
🏗️ Creating Your First HTTP Server
Let’s build a post office! Here’s the simplest one possible:
const http = require('http');
const server = http.createServer(
(request, response) => {
response.end('Hello, visitor!');
}
);
server.listen(3000);
console.log('Post office open!');
What just happened?
- We opened our toolkit (
http) - We created a server (our post office)
- We told it to listen at door 3000
- Every visitor gets a “Hello!”
graph TD A["📨 Visitor Arrives"] --> B["🏠Server Listens"] B --> C["📝 Read Request"] C --> D["✍️ Write Response"] D --> E["📤 Send Back"]
đź“© The Request Object: Reading the Letter
When someone visits your server, they send a request. It’s like a letter with important information!
What’s in the Request?
const server = http.createServer(
(req, res) => {
console.log(req.method);
// GET, POST, PUT, DELETE
console.log(req.url);
// /home, /about, /users
console.log(req.headers);
// Extra info about sender
res.end('Got your letter!');
}
);
Common Request Properties
| Property | What It Tells You | Example |
|---|---|---|
method |
What they want to do | GET = “Show me” |
url |
Where they want to go | /pizza |
headers |
Extra details | Browser type |
Real Example:
When you type
google.comin your browser, you send aGETrequest saying “show me the homepage!”
✉️ The Response Object: Writing Back
Now you need to reply! The response object is your pen and paper.
const server = http.createServer(
(req, res) => {
// Set the content type
res.setHeader(
'Content-Type',
'text/plain'
);
// Set status code
res.statusCode = 200;
// Write your message
res.write('Dear friend,\n');
res.write('Thanks for visiting!\n');
// Seal and send!
res.end('Goodbye!');
}
);
Response Superpowers
| Method | What It Does |
|---|---|
setHeader() |
Add info to envelope |
write() |
Write part of message |
end() |
Seal and send letter |
statusCode |
Tell if it worked |
đź“‹ HTTP Headers: The Envelope Details
Headers are like notes on the envelope. They tell extra information about your letter.
Request Headers (What visitor tells you)
// Check what browser they use
const browser = req.headers['user-agent'];
// Check what format they want
const wantJSON = req.headers['accept'];
Response Headers (What you tell visitor)
// Tell them it's HTML
res.setHeader(
'Content-Type',
'text/html'
);
// Tell them it's okay to cache
res.setHeader(
'Cache-Control',
'max-age=3600'
);
Common Headers Cheat Sheet
| Header | Meaning |
|---|---|
Content-Type |
“This is HTML/JSON/text” |
Content-Length |
“This big in bytes” |
Authorization |
“Here’s my password” |
User-Agent |
“I’m using Chrome” |
📤 Sending Different Responses
Your post office can send different types of mail!
Plain Text
res.setHeader(
'Content-Type',
'text/plain'
);
res.end('Just plain words!');
HTML Page
res.setHeader(
'Content-Type',
'text/html'
);
res.end('<h1>Pretty Title!</h1>');
JSON Data
res.setHeader(
'Content-Type',
'application/json'
);
res.end(
JSON.stringify({
message: 'Hello!',
success: true
})
);
🚦 HTTP Status Codes: Traffic Lights
Status codes are like traffic lights. They tell the visitor what happened!
graph TD A["Request Arrives"] --> B{What Happened?} B -->|All Good!| C["2xx ✅ Green Light"] B -->|Go Somewhere Else| D["3xx 🔄 Redirect"] B -->|You Made Error| E["4xx ❌ Your Fault"] B -->|Server Broke| F["5xx 💥 Our Fault"]
The Important Ones
| Code | Name | Meaning |
|---|---|---|
200 |
OK | Everything worked! âś… |
201 |
Created | New thing made! 🎉 |
301 |
Moved | It’s somewhere else now |
400 |
Bad Request | I don’t understand you |
404 |
Not Found | Doesn’t exist! 🔍 |
500 |
Server Error | Oops, we broke! đź’Ą |
Using Status Codes
// Success!
res.statusCode = 200;
res.end('Here you go!');
// Not found!
res.statusCode = 404;
res.end('Page not found :(');
// Error!
res.statusCode = 500;
res.end('Something broke!');
🚀 HTTP/2: The Faster Post Office
HTTP/2 is like upgrading from bicycles to motorcycles! It’s faster and smarter.
Why HTTP/2 is Better
| Old Way (HTTP/1) | New Way (HTTP/2) |
|---|---|
| One letter at a time | Many letters at once! |
| Wait for each reply | Replies come together |
| Repeat same headers | Smart header compression |
Using http2 Module
const http2 = require('http2');
const fs = require('fs');
const server = http2.createSecureServer({
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
});
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Super Fast!</h1>');
});
server.listen(3000);
Important: HTTP/2 needs HTTPS (secure connection) to work in browsers!
HTTP/2 Special Features
| Feature | What It Does |
|---|---|
| Multiplexing | Many requests at once |
| Server Push | Send files before asked |
| Header Compression | Smaller, faster headers |
| Streams | Better data flow |
🎯 Complete Working Example
Let’s build a real post office that handles different requests!
const http = require('http');
const server = http.createServer(
(req, res) => {
// Check where they want to go
if (req.url === '/') {
res.statusCode = 200;
res.setHeader(
'Content-Type',
'text/html'
);
res.end('<h1>Welcome Home!</h1>');
}
else if (req.url === '/about') {
res.statusCode = 200;
res.setHeader(
'Content-Type',
'text/plain'
);
res.end('About our server!');
}
else if (req.url === '/api/data') {
res.statusCode = 200;
res.setHeader(
'Content-Type',
'application/json'
);
res.end(JSON.stringify({
name: 'Server',
version: 1
}));
}
else {
res.statusCode = 404;
res.end('Page not found!');
}
}
);
server.listen(3000, () => {
console.log('Server running!');
});
🎉 You Did It!
You now understand how HTTP servers work! Remember:
- http module = Your toolkit
- Request = The incoming letter
- Response = Your reply
- Headers = Envelope details
- Status codes = Traffic lights
- HTTP/2 = Faster delivery!
You’re ready to build amazing web servers! 🚀
