Building an HTTP Server
💻 Node.jsCreate a server with the built-in http module and route requests by URL.
Before frameworks, Node could already serve HTTP. Understanding the raw module makes Express and similar tools much clearer.
- Create an HTTP server.
- Read the method and URL.
- Return status codes and JSON.
A Minimal Server
The callback runs for every request. It receives a request and a response object.
import { createServer } from "node:http";
const server = createServer((request, response) => {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello from Node");
});
server.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});Routing
Check the URL path and the method to decide what to send. Always end the response.
const server = createServer((request, response) => {
if (request.method === "GET" && request.url === "/health") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ status: "ok" }));
return;
}
response.writeHead(404, { "Content-Type": "application/json" });
response.end(JSON.stringify({ error: "Not found" }));
});Status Codes
Return 200 for success, 201 for created, 400 for bad input, 404 for missing resources and 500 for unexpected failures.
Practice
- Create a server that responds on / and returns 404 elsewhere.
- Add a /time route that returns the current time as JSON.
- Return 405 for a POST to a GET-only route.
Hands-on exercise
Build a server with:
1. GET / returns plain text 'Home'.
2. GET /status returns JSON with status ok and the current uptime.
3. Anything else returns 404 JSON.
Recap
The http module serves requests with a request and response object. Route on method and URL, and always send a status.
Example
import { createServer } from "node:http";
const server = createServer((request, response) => {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello from Node");
});
server.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});
Exercises
1. GET / returns plain text 'Home'.
2. GET /status returns JSON with status ok and the current uptime.
3. Anything else returns 404 JSON.
Expected Output
Home on /, JSON on /status and a 404 elsewhere.