Creating an HTTP Server
Before reaching for a framework, it's worth seeing what Node gives you for free: the built-in http module can start a real, working web server in just a few lines.
A minimal server
JS server.js
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello from the server!");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
bash terminal
node server.js
Output
Server running at http://localhost:3000/
The process doesn't exit after printing that — server.listen() keeps it alive, waiting for requests. The callback passed to http.createServer() runs once per incoming request, with req (the request) and res (the response you build and send back).
Routing by URL
There's no built-in router — you branch on req.url yourself:
JS server.js
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.end("Welcome to the homepage.");
} else if (req.url === "/about") {
res.end("This is the about page.");
} else {
res.statusCode = 404;
res.end("Not found.");
}
});
server.listen(3000);
bash terminal — in another window
curl http://localhost:3000/about curl -i http://localhost:3000/nowhere
Output
This is the about page. HTTP/1.1 404 Not Found ... Not found.
Setting res.statusCode before calling res.end() is how you send back something other than the default 200 OK.
Note: every response must eventually call
res.end() (with or without a body) — forget it, and the client just hangs, waiting for a response that never arrives, since Node has no idea you're "done" with that request otherwise.