Node.js Lesson 6: HTTP Server
Node.js can create HTTP servers without any external library. This is the foundation of web development with Node — understanding it makes Express (next lesson) much clearer.
Your First HTTP Server
const http = require("http");
const server = http.createServer((req, res) => {
// req = request (what the client sent)
// res = response (what we send back)
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Hello from Node.js server!</h1>");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
// Run: node server.js
// Open: http://localhost:3000
Handling Different Routes
const http = require("http");
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if (url === "/" && method === "GET") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Home Page</h1>");
} else if (url === "/about" && method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ page: "about", version: "1.0" }));
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
}
});
server.listen(3000, () => console.log("http://localhost:3000"));
🏋️ Practice Task
Build a server that returns different HTML pages for /, /about, /contact. Also handle a /api/time route that returns JSON with the current timestamp. Return 404 for all other routes.
💡 Hint: Check req.url for each route. Set Content-Type appropriately. JSON.stringify({time: new Date().toISOString()}) for the API route.