Your First HTTP Server in Node.js
From Zero to Handling Real Requests
Backend development begins with one simple idea:
Listen → Process → Respond
In Node.js, this is done using the built-in HTTP module. No frameworks needed.
Setting up a Simple Node.js App
Step 1: Initialize Project
mkdir first-server
cd first-server
npm init -y
Step 2: Create Entry File
touch index.js
HTTP Module
Node.js provides a built-in module called http to create servers.
Basic Server Example
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello World");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
What’s Happening Here?
Open browser:
http://localhost:3000
Understanding Request and Response Objects
Request Object (req)
Contains:
Example:
console.log(req.method);
console.log(req.url);
Response Object (res)
Used to send data back.
Methods:
Example:
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Response sent");
HTTP Methods
HTTP defines how clients interact with server.
GET (Fetch Data)
Used to retrieve data.
if (req.method === "GET" && req.url === "/") {
res.end("This is GET request");
}
POST (Send Data)
Used to send data to server.
if (req.method === "POST" && req.url === "/data") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
console.log(body);
res.end("Data received");
});
}
PUT (Update Data)
Used to update existing data.
if (req.method === "PUT" && req.url === "/update") {
res.end("Data updated");
}
DELETE (Remove Data)
Used to delete data.
if (req.method === "DELETE" && req.url === "/delete") {
res.end("Data deleted");
}
Sending and Receiving Data
Receiving Data (Request Body)
Node streams request data in chunks.
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
console.log("Received:", body);
});
Sending JSON Response
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({
message: "Success",
status: 200
}));
Routing Example (Handling Multiple Routes)
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
res.end("Home Page");
}
else if (req.method === "GET" && req.url === "/about") {
res.end("About Page");
}
else if (req.method === "POST" && req.url === "/data") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
res.end("Received Data");
});
}
else {
res.statusCode = 404;
res.end("Route Not Found");
}
});
server.listen(3000);
Key Observations
Common Mistakes Beginners Make
Mental Model
Everything revolves around:
req → process → res
Why This Matters
Before using Express or frameworks, this teaches you: