In this lesson, you followed requests into the server from the last lesson and logged what Node.js hands the request listener each time.
Key Points
node --watch server.tsrestarts the server every time you save. A running server keeps the code it started with, so watch mode saves you from stopping and starting it by hand.- Only one program can listen on a port at a time. If an old copy of the server is still running, a new one fails with
listen EADDRINUSE: address already in use. Stop the old copy with Ctrl+C (and the failed watch command too), then runnode --watch server.tsin one terminal. This time it prints the listening message. - Node.js calls your listener once for every request. Three
curlrequests meant three calls and three log lines. In the browser used here, one visit meant two: the page and/favicon.ico, the icon on the browser’s tab. Another browser might not ask for the icon. - The listener doesn’t run when the server starts, the way the rest of your file does. The listening message printed once per start, but the code inside the listener runs again for every request.
req.methodandreq.urldescribe this one request. For requests like the ones here,req.urlholds only the path and the query string, such as/plots?vacant=true, with no host name or port.req.headersis an object with lowercase header names, whatever the client sent.curlsentHost,User-AgentandAccept. Only log every header on your own machine, because headers can carry passwords. Once you’ve had your look, delete that line and save.- Between requests, the program waits. The listening server keeps it alive, and the event loop sits idle until the next request arrives.
So the rule is that each request means one call to your listener, and req holds that request.
The Final Code
Here’s server.ts after you’ve deleted the headers line, with one log line left in the listener:
server.ts
import { createServer } from "node:http";
const PORT = 3000;
const server = createServer((req, res) => {
console.log(req.method, req.url);
res.end("Hello from the Hollybank plot board!\n");
});
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
Started with node --watch server.ts and asked for plot 7 with curl -i http://localhost:3000/plots/7, it logs this line in the server’s terminal:
GET /plots/7
Your server still answers every request with the same plain text. In the next lesson, Send JSON With the Right Status, you’ll decide what goes back to the client.