You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Node.js includes a built-in http module that lets you create web servers without installing any external packages. Understanding it is the foundation for frameworks like Express.
const http = require("http");
const server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, World!");
});
server.listen(3000, function () {
console.log("Server running at http://localhost:3000/");
});
http.createServer() accepts a callback called a request listener. Node.js calls it every time a client sends an HTTP request. The callback receives two objects:
const server = http.createServer(function (req, res) {
console.log(req.method); // 'GET', 'POST', etc.
console.log(req.url); // '/about', '/api/users', etc.
console.log(req.headers); // object of request headers
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("OK");
});
const http = require("http");
const server = http.createServer(function (req, res) {
if (req.url === "/" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Home Page</h1>");
} else if (req.url === "/about" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>About Page</h1>");
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
}
});
server.listen(3000);
const http = require("http");
const server = http.createServer(function (req, res) {
if (req.url === "/api/status") {
const payload = JSON.stringify({ status: "ok", uptime: process.uptime() });
res.writeHead(200, { "Content-Type": "application/json" });
res.end(payload);
} else {
res.writeHead(404);
res.end();
}
});
server.listen(3000);
HTTP POST or PUT requests carry a body. Because bodies arrive in chunks (streams), you must collect them:
const server = http.createServer(function (req, res) {
if (req.method === "POST" && req.url === "/echo") {
let body = "";
req.on("data", function (chunk) {
body += chunk.toString();
});
req.on("end", function () {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(body);
});
}
});
Writing routing logic, body parsing, and error handling manually gets tedious fast. That is exactly why frameworks like Express exist — they wrap the http module with a clean, ergonomic API. But knowing how the raw module works makes debugging and understanding frameworks far easier.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.