Show contents
Chapter 2 of 7 · 20 min
A server with Node.js
By the end of this chapter, you'll be able to
- Write an HTTP server with the node:http module
- Read the method, path and parameters of a request
- Separate routing and logic into testable functions
- Read a request's body and reply in JSON
The smallest server
Node.js is an environment that runs JavaScript on a computer or a server, not only in a browser. Its built-in node:http module can receive HTTP requests. Save this code in server.js, then run node server.js in a terminal:
import { createServer } from "node:http";
const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ message: "Hello from the server!", path: req.url }));
});
server.listen(3000, () => console.log("Server ready on http://localhost:3000"));
Open http://localhost:3000/courses in your browser: it shows {"message":"Hello from the server!","path":"/courses"}. The function passed to createServer is called for each request, with two objects:
req(the request):req.method,req.url,req.headers;res(the response):res.writeHead(status, headers)thenres.end(body).
The file uses import, the module syntax: add "type": "module" to the project's package.json, or name the file server.mjs.
A testable router
Putting the whole API inside the createServer function quickly becomes unreadable. So we separate:
- a
router(method, path)function that chooses what to do; - handler functions that receive the request and return a
{ status, body }object instead of writing directly tores.
These functions do not depend on node:http: they can be tested by passing them fake requests, without starting a server.
const courses = [
{ id: 1, title: "Python: your first steps" },
{ id: 2, title: "SQL: your first queries" },
];
function listCourses() {
return { status: 200, body: courses };
}
function readCourse(params) {
const found = courses.find((c) => c.id === Number(params.id));
return found ? { status: 200, body: found } : { status: 404, body: { error: "unknown course" } };
}
const routes = [
{ method: "GET", pattern: "/api/courses", handle: listCourses },
{ method: "GET", pattern: "/api/courses/:id", handle: readCourse },
];
function match(pattern, path) {
const a = pattern.split("/");
const b = path.split("/");
if (a.length !== b.length) return null;
const params = {};
for (let i = 0; i < a.length; i++) {
if (a[i].startsWith(":")) params[a[i].slice(1)] = b[i];
else if (a[i] !== b[i]) return null;
}
return params;
}
function router(method, url) {
const path = url.split("?")[0];
for (const route of routes) {
const params = match(route.pattern, path);
if (route.method === method && params) return route.handle(params);
}
return { status: 404, body: { error: "unknown route" } };
}
console.log(router("GET", "/api/courses/2"));
console.log(router("GET", "/api/courses/7").status);
console.log(router("DELETE", "/api/courses/2").body);
{"status":200,"body":{"id":2,"title":"SQL: your first queries"}}
404
{"error":"unknown route"}
The pattern /api/courses/:id contains a parameter: :id matches any segment, whose value is retrieved in params.id. Careful: it is always text, hence the Number(...).
The method matches too: we call readCourse, which returns course no. 2.
Text description of the animation
- The path is split into segments on the / character.
- The first pattern has one segment less: no match.
- The second has 4 segments; 'api' and 'courses' are identical, and ':id' captures '2'.
- The method matches too: we call readCourse, which returns course no. 2.
Plugging the router into the server
The server only has to read the request, call router and write the response. A request's body arrives in chunks over the network: we gather them with a for await loop.
import { createServer } from "node:http";
async function readBody(req) {
let text = "";
for await (const chunk of req) text += chunk;
return text;
}
createServer(async (req, res) => {
const body = await readBody(req);
const { status, body: data } = router(req.method, req.url, body);
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
res.end(status === 204 ? undefined : JSON.stringify(data));
}).listen(3000);
This is the only piece that touches the network. The rest of the API will be made of ordinary functions, easy to read and to test.
Mini-lab: add a routeJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the chapters route
Add to the router a route GET /api/courses/:id/chapters that returns the list of a course's chapters, with a 404 if the course does not exist. Chapters are stored in a chapters object whose keys are the course identifiers.
Hint 1
api, courses, :id and chapters. The match function already handles it.Hint 2
chapters[id], or an empty array.Show the solution and common mistakes
const courses = [{ id: 1, title: "Python" }, { id: 2, title: "SQL" }];
const chapters = { 1: ["Variables", "Conditions"], 2: ["SELECT", "WHERE"] };
function listChapters(params) {
const id = Number(params.id);
if (!courses.some((c) => c.id === id)) return { status: 404, body: { error: "unknown course" } };
return { status: 200, body: chapters[id] ?? [] };
}
const routes = [{ method: "GET", pattern: "/api/courses/:id/chapters", handle: listChapters }];
function match(pattern, path) {
const a = pattern.split("/");
const b = path.split("/");
if (a.length !== b.length) return null;
const params = {};
for (let i = 0; i < a.length; i++) {
if (a[i].startsWith(":")) params[a[i].slice(1)] = b[i];
else if (a[i] !== b[i]) return null;
}
return params;
}
function router(method, url) {
const path = url.split("?")[0];
for (const route of routes) {
const params = match(route.pattern, path);
if (route.method === method && params) return route.handle(params);
}
return { status: 404, body: { error: "unknown route" } };
}
console.log(router("GET", "/api/courses/2/chapters"));
console.log(router("GET", "/api/courses/9/chapters"));
{"status":200,"body":["SELECT","WHERE"]}
{"status":404,"body":{"error":"unknown course"}}
Common mistakes:
- Returning
200with an empty list for a course that does not exist: the client can no longer tell "course without chapters" from "unknown course". - Comparing
c.id === params.idwithout conversion: the text"2"is never equal to the number2.
Summary
- 1Node.js runs JavaScript on a server; the node:http module receives HTTP requests.
- 2The createServer function receives req and res for each request.
- 3A router maps a method and a path pattern, such as /api/courses/:id, to a handler function.
- 4Functions that return { status, body } can be tested without starting a server.
- 5URL parameters are text: they must be converted.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.