Loading

T8 Node.js · Lesson 6

An HTTP server

The web runs on one simple exchange: a client asks, a server answers. Build a server with Node's http module, read each request's method, address, headers and body, answer with a status code, headers and a body, choose the answer by route, and test it all with fetch from the same program.

  • say what an HTTP request and response hold, and what a port is
  • start a server with http.createServer and listen, and close it again
  • read a request's method, URL, query and headers
  • answer with a status code, headers and a body, such as JSON
  • choose the answer by method and path: routes, and 404 for the rest
  • read a request's body, sent with fetch's POST, and answer 201 or 400
About 65 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-09); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-09)Play this lesson's games

The back cover

A web server is like the counter of a post office. Each visitor brings a request on a fixed form, and the clerk sends each one away with an answer: a stamp that says how it went, a few notes, and maybe a parcel. The counter never closes while the clerk is on duty.

These pages show that exchange in Node. They build a server with the http module and read each request's method, address, headers and body. They answer with a status code, headers and a body, choose the answer by route, and read the data that a client sends.

Before you start

The story: The questions at the door

Every morning, runners from the city's halls bring questions to the Engine Hall. What is the boiler's pressure? Is gate 6 open? May we send last night's readings?

The questions pile up at the great doors, because only the Foreman can answer them, and the Foreman cannot stand at the door all day. By noon the queue reaches the street.

"The engine knows every answer," says Foreman Tappet, and points at the doors. "Teach it to stand there. It must read each question, find the answer, and hand back a card that says how it went. Then the hall can answer the whole city."

Every page you open in a browser comes from a server: a program on some computer that waits for questions and answers them. The browser asks for a page; the server sends it back. The rules of that exchange are called HTTP.

Node can be that server. This lesson builds one with Node's own http module, reads the questions it receives, and sends back answers, the way every website and app on the internet does.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
How the web works.a browser asks, a server answersNow Node answers.
The parts of a URL.http://localhost:3000/gauges?unit=CEach part has a job.
The Network panel.status 200, 404The same codes, sent by you.
fetch and await.const r = await fetch(url);The client in every block.
JSON.JSON.stringify({ ok: true })The usual answer of a server.
Events and listeners.server.on("request", f)Each question is an event.
Streams.req.on("data", f)A request's body arrives as a stream.
The event loop.a waiting program stays aliveA server waits until it is closed.
Error codes.ENOENTECONNREFUSED and EADDRINUSE.
Ctrl+C.stops a running programHow a server is stopped by hand.

By the end of this lesson you will be able to:

  • say what an HTTP request and response hold, and what a port is;
  • start a server with http.createServer and listen, and close it again;
  • read a request's method, URL, query and headers;
  • answer with a status code, headers and a body, such as JSON;
  • choose the answer by method and path: routes, and 404 for the rest;
  • read a request's body, sent with fetch's POST, and answer 201 or 400.

How to follow this lesson

On the page, a server can be reached only by the same program, as the small Node's network lives in the page's memory. So every block is a server and its own client: it listens, asks itself with fetch, prints what it learnt, and closes the server. Each block has also been run in real Node 22, where the same program prints the same lines. On your own computer, you could also open the server's address in a browser.

In one line

This lesson is about HTTP servers: requests and responses, starting a server, reading requests, writing responses, routes, and request bodies.

Requests and responses

At a glance

The web runs on one simple exchange. A client, such as a browser, asks, and a server answers. Both speak HTTP, a fixed form for each message.

A request carries a method, such as GET, which says what the client wants done, and a path, which says what it wants. Then come headers, notes of the form name: value, and maybe a body of data. A response carries a status code, such as 200 OK or 404 Not Found, then headers and a body. A server listens at a port, a numbered door on its computer, and localhost means this same computer.

Take a guess: Can any program on Linux open port 80?

HTTP is a conversation of two messages. The client, such as a browser, sends a request; the server sends back a response.

Each message has a first line, then headers, which are notes of the form name: value, then, if needed, a body: the data itself.

PartIn a requestIn a response
the first linea method and a path: GET /gaugesa status code and its message: 200 OK
the headersHost, Accept, Content-Type, ...Content-Type, Content-Length, ...
the bodydata sent to the server, for a POSTthe answer itself: a page, text or JSON

Methods: what the client wants done

The method says what the client wants. Four of them do most of the work on the web:

MethodIt asks the server toExample
GETsend something backthe list of gauges
POSTtake something newa new reading
PUTreplace somethinga gauge's settings
DELETEremove somethingan old reading

Status codes: how it went

The status code is a number of three digits, and its first digit says what kind of answer it is. The status message after it says the same in words.

CodesMeaningThe ones you will meet most
2xxit worked200 OK, 201 Created, 204 No Content
3xxlook elsewhere301 Moved Permanently
4xxthe request was wrong400 Bad Request, 404 Not Found
5xxthe server failed500 Internal Server Error

Ports and localhost

One computer can run many servers, so each listens at a numbered door called a port. Web servers usually use port 80, or 443 for https; programs being built often use a number such as 3000.

The name localhost means this same computer, also written 127.0.0.1. So the address http://localhost:3000 means: this computer, port 3000.

The whole exchange in one program

Here is a server, and a client asking it a question, in one program. Read it now for its shape; each part has a section of its own below.

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  console.log("request:", req.method, req.url);
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("hello from the hall\n");
});
server.listen(3000, async () => {
  console.log("listening on 3000");
  const r = await fetch("http://localhost:3000/gauges?x=1");
  console.log(r.status, r.statusText, r.headers.get("content-type"));
  console.log(JSON.stringify(await r.text()));
  server.close(() => console.log("closed"));
});

Terminal: node app.js

listening on 3000
request: GET /gauges?x=1
200 OK text/plain
"hello from the hall\n"
closed

Follow the lines in order. The server started and listened at port 3000. The client's fetch sent a GET request for /gauges?x=1, and the server's function printed it.

The server answered 200 OK, with a Content-Type header of text/plain and a body of one line. The client read the status, the header and the body. Last, the server was closed, so that the program could end.

Worked example 1

The hall's clerk asks for three paths and wants to know, for each, whether the answer was a success.

What we have: a server that answers 200 for /boiler and 404 for anything else

What we need: for each path, its status code, its message and whether it worked

The plan: fetch each path in turn and print r.status, r.statusText and r.ok

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.statusCode = req.url === "/boiler" ? 200 : 404;
  res.end();
});
server.listen(3000, async () => {
  for (const path of ["/boiler", "/fan", "/"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, r.status, r.statusText, r.ok);
  }
  server.close();
});

Terminal: node app.js

/boiler 200 OK true
/fan 404 Not Found false
/ 404 Not Found false
  1. The server sets res.statusCode before it ends the response.
  2. The property r.ok is true for any status from 200 to 299, and false for the rest.
  3. A 404 is still an answer. fetch did not fail; it gave a response whose status says no such thing.

/boiler worked; /fan and / were Not Found.

Check: Only /boiler was given 200 by the server, and only its ok is true.

A path that fails: wrapping fetch in try and catch to find a 404. fetch throws only when no answer comes at all, such as when no server listens; a 404 comes back as an ordinary response.

When you are stuck: The parts of HTTP blur together

Ask three questions of every exchange: which method, which path, and which status code came back.

In the browser, the Network panel of DevTools shows every request and response with their headers and status.

A status code's first digit is enough to start: 2 is good, 4 is the request's fault, 5 is the server's.

Your turn

Which part of a response carries the answer itself, such as the page or the JSON?Tap to reveal
  1. The headers are notes about it.

The body.

What does the status code 404 say?Tap to reveal
  1. It is a 4xx code.

Not Found: there is no such thing at that path.

node -p 'require("http").STATUS_CODES[201]'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Created
  1. Node keeps every status message in STATUS_CODES.
  2. 201 is the code for something new that was made.

It prints Created.

Did you know?

Doors below 1024 are guarded

On Linux, the low ports are guarded. The Linux manual page for IP says that port numbers below 1024 are called privileged ports, and that only a privileged process may bind to them, such as one with the capability CAP_NET_BIND_SERVICE. So an ordinary program cannot open port 80 without extra permission, while port 3000 needs none.

Why it fits here: It answers this topic's question: on Linux, ports below 1024 need special permission, so port 3000 is free to use.

Source: Linux manual page: ip(7)

Sixteen million names for this computer

The address 127.0.0.1 is one of many. The internet's standards reserve every address that begins with 127, more than 16 million of them, for loopback: a packet sent to any of them comes back to the same computer. The host requirements standard, RFC 1122 of October 1989, says that such an address must never appear outside a host.

Why it fits here: It widens this topic's localhost: every address that begins with 127, not only 127.0.0.1, means this same computer.

Sources: Wikipedia: Localhost; RFC 1122: Requirements for Internet Hosts

In one line

A client sends a request: a method, a path, headers and maybe a body; the server sends a response: a status code and message, headers and a body. A port is the numbered door a server listens at.

A first server

At a glance

Node can be the server itself. Its built-in module http makes one in three calls.

The call http.createServer makes a server and takes a listener, a function that gets two things for each request: req, the request, and res, the response to fill in. The call listen opens a port, and close shuts it again. A server is an emitter, like any other, and each request is a request event. While a server listens, it keeps the program running, waiting for the next visitor, until close is called.

Take a guess: Can a server let the computer choose a free port for it?

Three calls make a server. http.createServer(listener) makes it, server.listen(port, callback) opens its door, and server.close(callback) shuts it again.

The listener is a function of two parameters, usually called req and res: the request that came in, and the response to fill in and send.

A server is an emitter

A server is an EventEmitter, like the bells of lesson 05. The function given to createServer is a listener of its request event, so the same server can be made with on:

app.js

const http = require("http");
const server = http.createServer();
server.on("request", (req, res) => res.end(`you asked for ${req.url}`));
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/pumps");
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

you asked for /pumps

Each request is one emit of request, with a new req and a new res. The server also announces listening when its door is open, and close when it has shut. The callbacks of listen and close are listeners of those two events:

app.js

const http = require("http");
const server = http.createServer((req, res) => res.end("hi"));
server.on("listening", () => console.log("listening event", server.address()));
server.listen(3000, () => {
  console.log("listen callback");
  server.close(() => console.log("close callback"));
  console.log("close asked");
});
server.on("close", () => console.log("close event"));
console.log("main done");

Terminal: node app.js

main done
listening event { address: '::', family: 'IPv6', port: 3000 }
listen callback
close asked
close event
close callback

The call to listen returns at once, which is why main done printed first. The door opens a moment later, from the event loop. The address :: means every address that the computer has, in the newer IPv6 style, and port is the door's number.

The close callback ran last, after the close event that it listens to.

A server keeps the program running

A program ends when its event loop has nothing left to wait for, as lesson 01 showed. A listening server is always waiting for its next request, so a program with a server never ends by itself. That is what a server is for: it runs for days, answering whoever comes.

Stopping a server

In a real terminal, a server program runs until you press Ctrl+C. The programs in this lesson close their own servers when they are done, so that they end. On this page, a program that leaves its server listening is stopped with a note instead, as the page cannot wait for visitors.

One port, one server

Only one server can listen at a port. A second one fails with the error code EADDRINUSE, address in use, which the server reports with its error event:

app.js

const http = require("http");
const a = http.createServer(() => {});
const b = http.createServer(() => {});
a.listen(3000, () => {
  b.on("error", (err) => {
    console.log(err.code, err.syscall, err.address, err.port);
    console.log(err.message);
    a.close();
  });
  b.listen(3000);
});

Terminal: node app.js

EADDRINUSE listen :: 3000
listen EADDRINUSE: address already in use :::3000

In real life the first server is often an earlier run of the same program, still running in another terminal. Stop it, or choose another port.

Worked example 2

Start a server, ask it two questions one after the other, and close it once both are answered. Print what each side does, to see the order.

What we have: a server that numbers its requests and answers with the number

What we need: both answers, in order, and the server closed at the end

The plan: listen; in the listen callback, fetch two paths in turn with await; then close

app.js

const http = require("http");
let n = 0;
const server = http.createServer((req, res) => {
  n += 1;
  console.log("server: request", n, req.url);
  res.end(`answer ${n}`);
});
server.listen(3000, async () => {
  for (const path of ["/first", "/second"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log("client:", await r.text());
  }
  server.close(() => console.log("server: closed"));
});

Terminal: node app.js

server: request 1 /first
client: answer 1
server: request 2 /second
client: answer 2
server: closed
  1. Asking starts only in the listen callback, when the door is open.
  2. await makes the client wait for each answer, so the second request comes after the first answer.
  3. close comes last, when both answers are in, and its callback prints after the server has shut.

Two answers, answer 1 and answer 2, then the server closed.

Check: The server's lines and the client's alternate, because each question waits for its answer.

A path that fails: closing the server right after listen, before the fetches. The fetches then find no server at the port and fail with the code ECONNREFUSED, connection refused.

When you are stuck: The server does not answer, or the program never ends

Ask only after the listen callback has run: before it, the door is not open.

Close the server when the program is done with it; in a real terminal, Ctrl+C stops it.

EADDRINUSE means that another server already listens at that port. Stop it, or use another port.

Your turn

Which call opens the server's door at a port?Tap to reveal
  1. createServer only makes the server.

server.listen(port, callback).

What does the error code EADDRINUSE say?Tap to reveal
  1. ADDR is short for address.

Another server already listens at that port.

node -e 'const s = require("http").createServer(); console.log(s.listening); s.listen(3000, () => { console.log(s.listening); s.close(); })'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
false
true
  1. Before listen, the server is not listening.
  2. In the listen callback, it is.

It prints false, then true.

Did you know?

Port 0 means any free port

A server can let the computer choose its door. Node's manual says that if listen is given port 0, or no port at all, the operating system picks an arbitrary unused port, and server.address().port reports it once the server is listening. Two servers started this way get two different ports, so they never fight over one.

Why it fits here: It answers this topic's question: listen(0) asks the system for any free port, and server.address().port tells which.

Source: Node.js manual: Net

Five minutes to ask

A server does not wait for ever. Since Node 18.0.0, its manual says, a server gives each client 3,00,000 milliseconds, five minutes, to send its whole request; after that it answers 408 and closes the connection. Before 18.0.0 there was no limit. The manual says the limit must stay above 0 to protect against denial-of-service attacks when no other server stands in front.

Why it fits here: It adds to this topic's server: since Node 18.0.0, a client has five minutes to send a request, or gets 408.

Source: Node.js manual: HTTP (server.requestTimeout)

In one line

http.createServer makes a server, an emitter whose request event brings req and res; listen opens its port, and a listening server keeps the program running until close.

Reading the request

At a glance

Every request arrives with three parts that a server reads first. They are the method, the address and the headers.

In the listener, req.method gives the method, such as GET or POST. The property req.url gives the path and the query, the part after a question mark, such as /gauges?unit=C. The headers sit in req.headers, under names in small letters. To take an address apart, new URL(req.url, base) gives its pathname and its searchParams, whose get method reads one value of the query. A missing value gives null.

Take a guess: Is there a limit on how big a request's headers can be?

The first parameter of the listener, req, is the request. Its three most used parts are req.method, req.url and req.headers. This server prints them for one request:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  console.log(req.method, req.url, req.httpVersion);
  console.log(req.headers);
  res.end();
});
server.listen(3000, async () => {
  await fetch("http://localhost:3000/a?b=1");
  server.close();
});

Terminal: node app.js

GET /a?b=1 1.1
{
  host: 'localhost:3000',
  connection: 'keep-alive',
  accept: '*/*',
  'accept-language': '*',
  'sec-fetch-mode': 'cors',
  'user-agent': 'node',
  'accept-encoding': 'gzip, deflate'
}

The method is GET, as fetch uses unless told otherwise. The url is only the path and the query, /a?b=1: the host and port are not in it. The version 1.1 is the version of HTTP that was used.

The headers are an object, every name in small letters. These are the ones that fetch sends by itself: host names the server being asked, accept says what kinds of answer the client can read, and user-agent names the client, here node. A browser sends more, and other values.

Headers of your own

A client can add headers of its own with fetch's headers option. The server finds each one under its name in small letters, whatever case the client used:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.end(`hello, ${req.headers["x-hall"]}`);
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/", { headers: { "X-Hall": "Clock Tower" } });
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

hello, Clock Tower

The path and the query

The part of an address after ? is its query: pairs of name=value, joined by &. To read them, turn req.url into a full URL object. new URL(req.url, base) needs a base for the host, and the request's own host header gives it:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  console.log(url.pathname, url.searchParams.get("gauge"), url.searchParams.get("nothing"));
  console.log(url.href);
  res.end();
});
server.listen(3000, async () => {
  await fetch("http://localhost:3000/readings?gauge=boiler&unit=C");
  server.close();
});

Terminal: node app.js

/readings boiler null
http://localhost:3000/readings?gauge=boiler&unit=C

url.pathname is the path alone, and url.searchParams.get(name) gives one value of the query, or null when the name is not there. searchParams also decodes the query: a space sent as %20 comes back as a space.

ExpressionFor GET /readings?gauge=boilerWhat it is
req.method'GET'the method, in capital letters
req.url'/readings?gauge=boiler'the path and the query
req.headers.host'localhost:3000'a header, under its small-letter name
url.pathname'/readings'the path alone
url.searchParams.get("gauge")'boiler'one value of the query, or null

Worked example 3

The gauge server answers /readings?gauge=NAME&unit=UNIT with the gauge's name and the unit, and uses C when no unit is given.

What we have: requests whose query names a gauge, and sometimes a unit

What we need: an answer such as boiler in F, or pump in C when the unit is missing

The plan: turn req.url into a URL; read gauge and unit from searchParams; put C where unit is null

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const gauge = url.searchParams.get("gauge");
  const unit = url.searchParams.get("unit") ?? "C";
  res.end(`${gauge} in ${unit}`);
});
server.listen(3000, async () => {
  for (const q of ["?gauge=boiler&unit=F", "?gauge=pump"]) {
    const r = await fetch("http://localhost:3000/readings" + q);
    console.log(await r.text());
  }
  server.close();
});

Terminal: node app.js

boiler in F
pump in C
  1. The base for new URL is built from the request's own host header.
  2. searchParams.get("unit") is null for the second request, and ?? replaces null with C.
  3. The path is the same for both requests; only the query changes.

boiler in F, and pump in C.

Check: The first query names a unit, F; the second names none, so the answer uses C.

A path that fails: cutting req.url at ? and & by hand. It works for this address, but values are left encoded, so a space sent as %20 stays %20, which searchParams would have decoded.

When you are stuck: The request's parts are not where you expect

req.url holds only the path and the query. Make a full URL with new URL(req.url, base) to take it apart.

Header names are in small letters: req.headers["content-type"], never req.headers["Content-Type"].

searchParams.get gives null for a name that is not in the query. Use ?? for a default.

Your turn

For a request to http://localhost:3000/a?b=1, what does req.url hold?Tap to reveal
  1. The host and port are not part of it.

'/a?b=1': the path and the query.

How does the server read a header that the client sent as Content-Type?Tap to reveal
  1. Node lowers every header name.

req.headers["content-type"].

node -p 'new URL("/r?gauge=boiler", "http://localhost").searchParams.get("gauge")'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
boiler
  1. The base gives the host; the path and query come from the first argument.
  2. searchParams reads the query.

It prints boiler.

Did you know?

A size limit on headers

Headers cannot be endless. Node's manual says the most it accepts for the headers of a request is 16 KiB by default, raised from 8 KiB in Node 13.13.0, and the option --max-http-header-size changes it. Since Node 12.0.0, a request whose headers are too big gets the answer 431 Request Header Fields Too Large.

Why it fits here: It answers this topic's question: a request's headers may be at most 16 KiB by default, or Node answers 431.

Sources: Node.js manual: Command-line options; Node.js manual: HTTP (Event: 'clientError')

Two headers with one name

A request may carry the same header twice. Node's manual says how req.headers folds such twins. Duplicates of some headers, such as host, content-type and user-agent, are thrown away; set-cookie always becomes an array; and the values of most other headers are joined with a comma. So one name in req.headers can hold two values.

Why it fits here: It adds to this topic's req.headers: a repeated header is dropped, kept in an array, or joined with commas, by its name.

Source: Node.js manual: HTTP (message.headers)

In one line

req.method is the method, req.url the path and query, req.headers the headers under small-letter names; new URL(req.url, base) gives pathname and searchParams.

Writing the response

At a glance

The second half of the exchange is the answer, and Node hands it to you half made, as res.

A response needs three things, in order: a status code, headers, and a body. The status code is set with res.statusCode, or with res.writeHead together with the headers. One header is set with res.setHeader. The body goes out with res.write, in pieces, and res.end, which sends the last piece and finishes. The header Content-Type tells the client what the body is, such as text/plain or application/json. Headers travel first, so once the body has started, it is too late to set them.

Take a guess: What does a browser do with an answer that has no Content-Type?

The second parameter of the listener, res, is the response, waiting to be filled in. A response needs three things: a status code, headers, and a body. Its methods set them in that order:

CallWhat it does
res.statusCode = 404sets the status code; 200 if you set nothing
res.setHeader("Content-Type", "text/plain")sets one header
res.writeHead(201, { ... })sets the status and headers at once, and gives back res
res.write("...")sends a piece of the body
res.end("...")sends the last piece, or the whole body, and finishes the response

Every response must be finished with end. Until then, the client keeps waiting for the rest.

Status codes and their messages

Node writes the status message for you, from its own table of codes. fetch reads the code into r.status and the message into r.statusText, and r.ok is true only for the 2xx codes:

app.js

const http = require("http");
const codes = [200, 201, 204, 400, 404, 405, 500];
const server = http.createServer((req, res) => {
  res.statusCode = Number(req.url.slice(1));
  res.end(res.statusCode === 204 ? undefined : "x");
});
server.listen(3000, async () => {
  for (const c of codes) {
    const r = await fetch("http://localhost:3000/" + c);
    console.log(r.status, r.statusText, r.ok, JSON.stringify(await r.text()));
  }
  server.close();
});

Terminal: node app.js

200 OK true "x"
201 Created true "x"
204 No Content true ""
400 Bad Request false "x"
404 Not Found false "x"
405 Method Not Allowed false "x"
500 Internal Server Error false "x"

The 204 response has no body at all, as its name, No Content, says. The server sent none, and the client read an empty string.

Headers: yours, and Node's

The header Content-Type tells the client what the body is, so that it can read it: text/plain for plain text, text/html for a page, application/json for JSON. Node also adds headers of its own. This program asks for three paths and lists the names of the headers that each answer carried:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  if (req.url === "/a") {
    res.setHeader("Content-Type", "text/plain");
    res.end("one");
  } else if (req.url === "/b") {
    res.writeHead(200, { "Content-Type": "application/json", "X-Hall": "engine" });
    res.end(JSON.stringify({ ok: true }));
  } else {
    res.write("part 1, ");
    res.end("part 2");
  }
});
server.listen(3000, async () => {
  for (const p of ["/a", "/b", "/c"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, [...r.headers.keys()].join(" "), r.headers.get("content-type"), await r.text());
  }
  server.close();
});

Terminal: node app.js

/a connection content-length content-type date keep-alive text/plain one
/b connection content-type date keep-alive transfer-encoding x-hall application/json {"ok":true}
/c connection date keep-alive transfer-encoding null part 1, part 2

Node added date, the time of the answer, which this lesson never prints as it changes every second. It added connection and keep-alive, which keep the connection open for more requests.

When the whole body came with end, Node sent content-length, the body's size in bytes. After writeHead or write, the body was sent in pieces, and Node said so with transfer-encoding: chunked. The answer to /c had no content-type, because the server set none.

Too late for headers

Headers travel before the body. Once the response has started, they can no longer be changed, and Node refuses with the error code ERR_HTTP_HEADERS_SENT:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.end("done");
  try {
    res.setHeader("X-Late", "1");
  } catch (e) {
    console.log(e.code, e.message);
  }
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

ERR_HTTP_HEADERS_SENT Cannot set headers after they are sent to the client
done

Worked example 4

Make a /status address that answers JSON: the hall's name and how many gauges it has, with the status 200 and the right Content-Type. The client reads it with r.json().

What we have: the hall's name, Engine Hall, and 3 gauges

What we need: a JSON answer that the client turns back into an object

The plan: turn the data into text with JSON.stringify; writeHead with 200 and application/json; end with the text; read it with r.json()

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  const body = JSON.stringify({ hall: "Engine Hall", gauges: 3 });
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(body);
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/status");
  console.log(r.status, r.headers.get("content-type"));
  const data = await r.json();
  console.log(data.hall, data.gauges + 1);
  server.close();
});

Terminal: node app.js

200 application/json
Engine Hall 4
  1. The body must be text or bytes, so the object goes through JSON.stringify first.
  2. The Content-Type of application/json tells any client that the text is JSON.
  3. r.json() reads the body and parses it, so data.gauges is a number again, and 3 + 1 is 4.

The client got 200 and the object back, and printed Engine Hall 4.

Check: The data that went in, the hall's name and 3, came out on the client's side.

A path that fails: res.end({ hall: "Engine Hall" }), without JSON.stringify. A body must be text or bytes, so Node refuses the object with the error code ERR_INVALID_ARG_TYPE.

When you are stuck: The client gets the wrong answer, or none

Finish every response with res.end, on every path through the listener.

Set the status and headers before the body: after the first write or end it is too late.

Send objects as JSON.stringify(data), with the Content-Type application/json.

Your turn

Which header tells the client that the body is JSON?Tap to reveal
  1. Its value is application/json.

Content-Type.

What does res.writeHead(201, { ... }) do?Tap to reveal
  1. It sets two things at once.

It sets the status code and the headers together.

node -p 'require("http").STATUS_CODES[500]'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Internal Server Error
  1. 500 is the first of the 5xx codes.
  2. They mean that the server failed.

It prints Internal Server Error.

Did you know?

Browsers guess a missing type

An answer without Content-Type leaves the client to guess. MDN says that when there is no type, browsers may perform MIME sniffing: guessing the type by looking at the bytes, each browser in its own way. A server that wants its types obeyed sends X-Content-Type-Options: nosniff, which says that the types in its Content-Type headers should be respected and not changed.

Why it fits here: It answers this topic's question: a browser guesses a missing type from the bytes, which nosniff tells it not to do.

Sources: MDN: MIME types; MDN: X-Content-Type-Options; WHATWG Fetch Standard: X-Content-Type-Options; WHATWG MIME Sniffing Standard

Five seconds of keep-alive

Node keeps a connection open after an answer, ready for the next request, but not for long. Its manual says that by default a server waits 5 seconds, 5000 milliseconds, for more data after it finishes the last response, and then destroys the socket. Node 24.6.0 and 22.19.0 added a buffer of 1 second more, to reduce connection reset errors.

Why it fits here: It adds to this topic's keep-alive header: Node keeps an idle connection open for 5 seconds by default, plus a 1-second buffer.

Source: Node.js manual: HTTP (server.keepAliveTimeout)

In one line

A response is a status code, headers and a body: statusCode or writeHead, setHeader, then write and end; Content-Type says what the body is, and headers must come before the body.

Routes: one server, many answers

At a glance

A real server answers many questions with one listener. It needs a way to tell them apart.

A route is a pair of a method and a path that the server knows how to answer, such as GET /gauges. The listener looks at req.method and the pathname and chooses what to do, with if statements or with a table of routes. A path the server does not know gets 404 Not Found. A known path asked with a method it does not accept gets 405 Method Not Allowed.

Take a guess: Are /Gauges and /gauges the same path?

A real server answers many questions: the list of gauges, one gauge, a new reading. Each pair of a method and a path that the server knows how to answer is called a route, such as GET /gauges.

The listener is one function for every request, so it looks at the method and the path, and chooses what to do. Everything else gets 404 Not Found.

Choosing with if

This server knows two kinds of route: GET /gauges for the whole list, and GET /gauges/NAME for one gauge. A small helper, send, writes the status, the header and the JSON in one place:

app.js

const http = require("http");
const gauges = { boiler: 95, pump: 40 };
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  const send = (status, data) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  };
  if (req.method === "GET" && url.pathname === "/gauges") send(200, gauges);
  else if (req.method === "GET" && url.pathname.startsWith("/gauges/")) {
    const name = url.pathname.slice("/gauges/".length);
    if (name in gauges) send(200, { name, value: gauges[name] });
    else send(404, { error: `no gauge called ${name}` });
  } else send(404, { error: "not found" });
});
server.listen(3000, async () => {
  for (const p of ["/gauges", "/gauges/pump", "/gauges/fan", "/nothing"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(r.status, JSON.stringify(await r.json()));
  }
  const r = await fetch("http://localhost:3000/gauges", { method: "DELETE" });
  console.log(r.status, await r.text());
  server.close();
});

Terminal: node app.js

200 {"boiler":95,"pump":40}
200 {"name":"pump","value":40}
404 {"error":"no gauge called fan"}
404 {"error":"not found"}
404 {"error":"not found"}

The path /gauges/pump starts with /gauges/, and the rest of it, pump, is the gauge's name. The name fan is not in the object, so its answer is 404 with a message that says why.

The last request used DELETE, which no route here accepts, so it fell through to the final else: 404.

A table of routes

A chain of if grows long. Another way keeps the routes in an object, each one under a key made of the method and the path, and looks the request up in it:

app.js

const http = require("http");
const routes = {
  "GET /health": () => [200, { ok: true }],
  "GET /gauges": () => [200, ["boiler", "pump"]],
};
const server = http.createServer((req, res) => {
  const { pathname } = new URL(req.url, "http://localhost");
  const route = routes[`${req.method} ${pathname}`];
  const [status, data] = route ? route() : [404, { error: "not found" }];
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data));
});
server.listen(3000, async () => {
  for (const [method, path] of [["GET", "/health"], ["GET", "/gauges"], ["POST", "/gauges"], ["GET", "/nothing"]]) {
    const r = await fetch("http://localhost:3000" + path, { method });
    console.log(method, path, r.status, JSON.stringify(await r.json()));
  }
  server.close();
});

Terminal: node app.js

GET /health 200 {"ok":true}
GET /gauges 200 ["boiler","pump"]
POST /gauges 404 {"error":"not found"}
GET /nothing 404 {"error":"not found"}

The key for each request is built the same way, such as GET /health, so finding a route is one lookup. A new route is one more line in the object. The APIs track, which comes next, uses Express, a package that keeps such a table for you.

RequestRoute found?Answer
GET /gaugesyes200 and the data
GET /nothingno such path404 Not Found
DELETE /gaugesthe path exists, not with this method404 here; 405 Method Not Allowed is more exact

Worked example 5

Answer 405 Method Not Allowed, rather than 404, when the path exists but not with the method that was used, and say which methods it accepts.

What we have: one path, /gauges, which accepts only GET

What we need: 200 for GET, and 405 with a helpful message for DELETE

The plan: keep the methods of each path in an object; with no path, 404; with the path but not the method, 405; otherwise call the route

app.js

const http = require("http");
const routes = { "/gauges": { GET: () => [200, ["boiler", "pump"]] } };
const server = http.createServer((req, res) => {
  const { pathname } = new URL(req.url, "http://localhost");
  const methods = routes[pathname];
  let status, data;
  if (!methods) [status, data] = [404, { error: "not found" }];
  else if (!methods[req.method]) [status, data] = [405, { error: `use ${Object.keys(methods).join(", ")}` }];
  else [status, data] = methods[req.method]();
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data));
});
server.listen(3000, async () => {
  for (const method of ["GET", "DELETE"]) {
    const r = await fetch("http://localhost:3000/gauges", { method });
    console.log(method, r.status, r.statusText, JSON.stringify(await r.json()));
  }
  server.close();
});

Terminal: node app.js

GET 200 OK ["boiler","pump"]
DELETE 405 Method Not Allowed {"error":"use GET"}
  1. routes[pathname] finds the path's methods, or undefined for an unknown path.
  2. methods[req.method] finds the route, or undefined for a method that the path does not accept.
  3. Object.keys(methods) names the methods that the path does accept, for the error message.

GET gets 200; DELETE gets 405 Method Not Allowed and the hint use GET.

Check: Only GET is listed under /gauges, so only GET reaches a route.

A path that fails: a single key like GET /gauges for everything. The server can then tell only found from not found, and a client using the wrong method is told 404, as if the path did not exist.

When you are stuck: A route never matches

Print the key you build, such as `${req.method} ${pathname}`, next to the keys in your table.

The query is not part of the pathname: /gauges?x=1 has the path /gauges.

A slash at the end makes another path: /gauges/ is not /gauges.

Your turn

Which status code answers a path that the server does not know?Tap to reveal
  1. A 4xx code: the request was wrong.

404 Not Found.

Which status code says that the path exists, but not with this method?Tap to reveal
  1. Its message says the method is not allowed.

405 Method Not Allowed.

node -p 'const u = new URL("/gauges?x=1", "http://h"); "GET " + u.pathname'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
GET /gauges
  1. The pathname leaves out the query.
  2. The key joins the method and the pathname.

It prints GET /gauges.

Did you know?

Capital letters count in paths

Two addresses can differ only in capitals. The URI standard, RFC 3986, says that the scheme and the host are case-insensitive, so HTTP://www.EXAMPLE.com/ and http://www.example.com/ are the same. The other parts, the path among them, are case-sensitive unless a scheme says otherwise. So a route for /gauges does not answer /Gauges unless the server is written to.

Why it fits here: It answers this topic's question: /Gauges and /gauges are different paths, though the host's capitals do not matter.

Source: RFC 3986: Uniform Resource Identifier (URI): Generic Syntax

Gone, not just missing

HTTP has a stronger word than 404. The HTTP standard, RFC 9110, says that 410 Gone means the resource is no longer available and that this is likely to be permanent, so that links to it should be removed. It adds that a server that does not know whether the loss is permanent ought to use 404 Not Found instead.

Why it fits here: It adds to this topic's 404: 410 Gone says a path is gone for good, while 404 makes no such promise.

Source: RFC 9110: HTTP Semantics

In one line

A route is a method and a path that the server knows; the listener chooses by req.method and the pathname, and answers 404 for unknown paths, or 405 for a method the path does not accept.

Bodies: data sent to the server

At a glance

A GET only asks. A POST also carries data to the server, such as a new reading, in its body.

On the server, req is a readable stream, so the body arrives in chunks, read with data and end events or with for await. Only when all of it has arrived can it be parsed, for example with JSON.parse, inside try, since a client can send anything. A good answer to a new record is 201 Created. A body that cannot be read gets 400 Bad Request.

Take a guess: Can a client ask a server's permission before it sends a big body?

A GET only asks. A POST carries data to the server in its body, such as a new reading. On the client's side, fetch takes three more options: the method, a Content-Type header that says what the body is, and the body itself, as text.

On the server's side, the body arrives the way lesson 05's streams did, because req is a readable stream. Its data events bring the body in chunks, and its end event says that all of it has arrived. Only then can it be parsed:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  let body = "";
  req.on("data", (chunk) => { body += chunk; });
  req.on("end", () => {
    console.log("server got", JSON.stringify(body), req.headers["content-type"], req.headers["content-length"]);
    try {
      const data = JSON.parse(body);
      res.writeHead(201, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ saved: data }));
    } catch {
      res.writeHead(400, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "not JSON" }));
    }
  });
});
server.listen(3000, async () => {
  for (const body of ['{"gauge":"boiler","value":95}', "boiler 95"]) {
    const r = await fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body });
    console.log(r.status, await r.json());
  }
  server.close();
});

Terminal: node app.js

server got "{\"gauge\":\"boiler\",\"value\":95}" application/json 29
201 { saved: { gauge: 'boiler', value: 95 } }
server got "boiler 95" application/json 9
400 { error: 'not JSON' }

The first body was valid JSON, 29 bytes long, as content-length said. The server parsed it and answered 201 Created, the code for something new that was stored.

The second body, boiler 95, was not JSON, so JSON.parse threw, the catch caught it, and the server answered 400 Bad Request: the client sent something wrong. The server itself kept running.

The body with for await

Like any readable stream, req works with for await. In an async listener, a loop collects the body, and the code reads from top to bottom. This is the shape of a small store of readings:

Worked example 6

Make a small store: POST /readings adds a reading sent as JSON and answers 201 with the number stored; GET /readings lists them all; a body that is not JSON gets 400.

What we have: an empty array of readings, and three bodies to send, the last one broken

What we need: two readings stored, one refused, and the list of the two

The plan: in an async listener, collect the body with for await, parse it inside try, push it, and answer 201; answer 400 in the catch; list on GET

app.js

const http = require("http");
const readings = [];
const server = http.createServer(async (req, res) => {
  const send = (status, data) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  };
  if (req.method === "POST" && req.url === "/readings") {
    let body = "";
    for await (const chunk of req) body += chunk;
    try {
      readings.push(JSON.parse(body));
      send(201, { saved: readings.length });
    } catch {
      send(400, { error: "the body is not JSON" });
    }
  } else if (req.method === "GET" && req.url === "/readings") send(200, readings);
  else send(404, { error: "not found" });
});
server.listen(3000, async () => {
  const post = (body) => fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body });
  for (const body of [JSON.stringify({ gauge: "boiler", value: 95 }), JSON.stringify({ gauge: "pump", value: 40 }), "pump 40"]) {
    const r = await post(body);
    console.log(r.status, JSON.stringify(await r.json()));
  }
  const r = await fetch("http://localhost:3000/readings");
  console.log(r.status, JSON.stringify(await r.json()));
  server.close();
});

Terminal: node app.js

201 {"saved":1}
201 {"saved":2}
400 {"error":"the body is not JSON"}
200 [{"gauge":"boiler","value":95},{"gauge":"pump","value":40}]
  1. for await over req waits for every chunk of the body; when the loop ends, the body is complete.
  2. JSON.parse runs inside try, so a broken body becomes a 400 for that client alone.
  3. The array lives as long as the server, so the GET at the end sees both readings.

Two readings stored with 201, one refused with 400, and the list holds the two.

Check: The counts went 1, then 2; the broken body changed nothing; the list has exactly the two good readings.

A path that fails: JSON.parse(body) with no try around it. A client that sends a broken body then makes the listener throw, and the whole server stops, for every client, not just that one.

Node's older client: http.get

Before fetch came to Node, programs asked servers with http.get. It is still common in older code. Its response is a readable stream too, read with data and end:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "text/plain");
  res.end("pong");
});
server.listen(3000, () => {
  http.get("http://localhost:3000/ping", (res) => {
    console.log(res.statusCode, res.statusMessage, res.headers["content-type"]);
    let body = "";
    res.on("data", (c) => { body += c; });
    res.on("end", () => { console.log("body:", body); server.close(); });
  });
});

Terminal: node app.js

200 OK text/plain
body: pong

Its response gives statusCode and statusMessage, and its headers as an object under small-letter names, like req.headers. fetch is shorter and gives promises, and the browser has it too, so new code uses fetch.

When you are stuck: The body is empty, or half read

Read the body until its end event, or to the end of a for await loop. Before that, part of it may still be on its way.

On the client's side, give fetch a method such as POST, a Content-Type, and a body that is text: JSON.stringify(data).

Parse inside try, and answer 400 when the body is broken, so that one bad client cannot stop the server.

Your turn

Which event of req says that the whole body has arrived?Tap to reveal
  1. It is a readable stream.

end.

Which status code should a server give for a body it cannot read?Tap to reveal
  1. The client sent something wrong.

400 Bad Request.

node -p 'Buffer.byteLength(JSON.stringify({ gauge: "boiler", value: 95 }))'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
29
  1. JSON.stringify gives the text that fetch sends.
  2. Each of its characters takes one byte.

It prints 29, the content-length that the server saw.

Did you know?

Asking before sending

A client with a big body can ask first. It sends the header Expect: 100-continue and waits. The curl book says curl does this by default for a POST known or suspected to be larger than one megabyte, and sends the body once the server answers 100. Node's manual says a server that does not listen for checkContinue answers 100 Continue as appropriate.

Why it fits here: It answers this topic's question: Expect: 100-continue lets a client ask before it sends a big body, and Node says yes by default.

Sources: Everything curl: Expect 100-continue; Node.js manual: HTTP (Event: 'checkContinue')

Undici, which means eleven

Node's fetch has a name of its own underneath. The Node manual says its fetch is based on undici, an HTTP/1.1 client written from scratch for Node.js, and process.versions.undici gives the version inside. The project's own page explains the name: undici means eleven in Italian, from HTTP/1.1, and it is also a Stranger Things reference.

Why it fits here: It adds to this topic's fetch: Node's fetch runs on undici, an HTTP/1.1 client named after the Italian for eleven.

Sources: Node.js manual: Globals (fetch); undici on GitHub (README)

In one line

A POST carries data in its body; req is a readable stream, read with data and end or for await; parse the body inside try, and answer 201 Created, or 400 Bad Request when it is broken.

Where it is used

Every website and every app that talks to the internet runs on requests and responses. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
requests and responsesevery page and every appa browser asking a shop's server for a product page
ports and localhostbuilding and testing on your own computera project's npm start, serving at localhost:3000
status codesevery answerthe 404 page of a missing product; 500 when a server breaks
routesAPIs: servers that answer programsGET /products and POST /orders in a shop's API
JSON bodiesapps that send forms and dataa phone app sending a new order to its server
fetchclients, in the browser and in Nodea page loading prices; one server asking another

The Foreman's great doors are the server, each numbered door is a port, and each runner's question is a request. The card handed back is the response: its number on top is the status code, and the answer below it is the body.

Mistakes and debugging

These are the slips that people meet most often with servers. Every output below is the real one, from the code shown.

1. Asking a server that is not listening

app.js

fetch("http://localhost:3000/").then(
  (r) => console.log("got", r.status),
  (e) => { console.log(e.name, e.message); console.log(e.cause.code, e.cause.message); }
);

Terminal: node app.js

TypeError fetch failed
ECONNREFUSED connect ECONNREFUSED 127.0.0.1:3000

No server listened at port 3000, so the connection was refused, and fetch failed with that as its cause. The fix: start the server first, ask only after its listen callback, and check the port.

2. Reading the body before it has arrived

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  let body = "";
  req.on("data", (chunk) => { body += chunk; });
  res.end(`got: ${body}`);
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/", { method: "POST", body: "boiler 95" });
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

got: 

The body comes after the listener has started, in data events. end ran at once, while body was still empty. The fix: answer inside the end listener, or after a for await loop over req.

3. A header name in capitals

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.end(`${req.headers["Content-Type"]} and ${req.headers["content-type"]}`);
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

undefined and application/json

Node lowers every header name. The fix: req.headers["content-type"], in small letters.

4. Expecting fetch to throw for a 404

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.writeHead(404, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ error: "no such gauge" }));
});
server.listen(3000, async () => {
  try {
    const r = await fetch("http://localhost:3000/gauges/fan");
    const data = await r.json();
    console.log("success?", data);
  } catch (e) {
    console.log("caught", e.message);
  }
  server.close();
});

Terminal: node app.js

success? { error: 'no such gauge' }

A 404 is an answer, so fetch did not throw, and the program took the error for data. The fix: check r.ok or r.status before using the body.

5. An object as the body

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  try {
    res.end({ hall: "Engine Hall" });
  } catch (e) {
    console.log(e.code);
    console.log(e.message);
    res.end("sorry");
  }
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(r.status, await r.text());
  server.close();
});

Terminal: node app.js

ERR_INVALID_ARG_TYPE
The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
200 sorry

A body travels as text or bytes. The fix: res.end(JSON.stringify(data)), with the Content-Type application/json.

Two slips that make something wait forever

A response that is never finished with res.end leaves its client waiting, and a server that is never closed keeps its program running. In a real terminal, Ctrl+C stops such a program; on this page, a server left listening stops with a note. End every path through the listener, and close the server when the program is done with it.

The debugging corner: what came in, and what went out?

Print req.method and req.url at the top of the listener, to see every request. On the client's side, print r.status and the headers you need. In a real terminal, curl -i http://localhost:3000/ shows a response's status line and headers as well as its body, and in a browser the Network panel of DevTools shows the same.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

app.js

const http = require("http");
const server = http.createServer((req, res) => {                 // one listener for every request
  const { pathname } = new URL(req.url, "http://localhost");     // the path, without the query
  if (req.method === "GET" && pathname === "/hello") {
    res.writeHead(200, { "Content-Type": "application/json" });  // the status and headers first
    res.end(JSON.stringify({ hello: "city" }));                  // then the body, and finish
  } else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "not found" }));
  }
});
server.listen(3000, async () => {                                // the door is open
  const r = await fetch("http://localhost:3000/hello");
  console.log(r.status, await r.json());
  server.close();                                                // close, so that the program ends
});

Terminal: node app.js

200 { hello: 'city' }
When you seeIt meansDo
fetch failed, ECONNREFUSEDno server listens at that portstart it; ask in its listen callback; check the port
EADDRINUSEanother server has the portstop it, or use another port
ERR_HTTP_HEADERS_SENTheaders changed after the body beganset the status and headers first
ERR_INVALID_ARG_TYPE from endthe body is not text or bytesJSON.stringify the object
404 from your own serverno route matchedprint the method and the pathname
the client waits forevera response was never finishedend every path with res.end
the program never endsa server still listensserver.close(), or Ctrl+C

The story: Open doors

You set the engine at a numbered door. It reads each question: what the runner wants done, to which thing, the notes pinned to it, and any parcel it carries. It finds the right answer for that question, and hands back a card with a number on top: 200 for found, 201 for noted, 404 for no such thing. Below the number is the answer, written in the tidy form that every hall can read.

By noon the queue is gone. Runners come and go all day, and nobody waits.

At night the Foreman locks the door, and the engine rests. "Tomorrow," she says, "the Couriers' Yard. They carry such questions between all the halls, by the thousand."

Reagents gathered: server, request, response, status code, route, port.

Sources

  • The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
  • MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)