Day 73 Node.js HTTP Server
Node.js built-in http module se web server bana sakte hain bina kisi framework ke. Yeh samajhna zaroori hai ke Express.js andar kaise kaam karta hai.
Basic HTTP Server
Pehla web server banao Node.js se.
const http = require("http");
const server = http.createServer((req, res) => {
const { method, url } = req;
console.log(`${method} ${url}`);
// Routes
if (method === "GET" && url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Welcome to CodingSkillUp API!</h1>");
} else if (method === "GET" && url === "/api/users") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify([
{ id: 1, name: "Zohaib" },
{ id: 2, name: "Ali" }
]));
} else if (method === "POST" && url === "/api/users") {
let body = "";
req.on("data", chunk => body += chunk);
req.on("end", () => {
const user = JSON.parse(body);
res.writeHead(201, { "Content-Type": "application/json" });
res.end(JSON.stringify({ id: Date.now(), ...user }));
});
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Route not found" }));
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
🎯 Practice Challenge
HTTP server banao with 5 routes — GET /, GET /users, GET /users/:id, POST /users, DELETE /users/:id. JSON responses return karo.