Node.jsbeginner 8 min
Build a tiny HTTP server with the built-in http module and see requests and responses.
How a server receives a request and sends back a response, using only Node's built-in http module.
Every website and API is a server answering requests. Seeing the smallest possible one removes the mystery before you meet frameworks like Express.
The web works as request and response. A browser sends a request (a URL and a method such as GET). A server sends a response (a status code, headers and a body).
Node's http.createServer takes a function called for every request. That function receives:
req: information about the request, such as req.url and req.method.res: your tool for answering. res.writeHead(200, {...}) sets the status and headers and res.end("text") sends the body.server.listen(3000) starts waiting for connections on port 3000.
Save as server.mjs:
createServer is given a function that runs once per request./, we answer status 200 (OK) with plain text./api/time, we answer with JSON. JSON.stringify turns an object into a string.404, meaning "not found".listen(3000, ...) starts the server and prints a line. Open http://localhost:3000 in a browser to try it. Stop it with Ctrl+C.Run it on your machine and visit the three URLs. The terminal output when it starts is below.
res.end(), so the browser waits forever.res.end needs a string or Buffer, so stringify first.http.createServer + listen is the core of every Node web app.You finished the Node.js beginner section. Next: Express, REST APIs and environment variables.
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello from my first server");
} else if (req.url === "/api/time") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
});
server.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});