Step 2: The first route
Start with the smallest working server: an in-memory array and one route that lists it. A helper send(res, status, data) sets the status and writes JSON, so every route answers the same way. In this demo the server starts on a free port, a request is made, and the server stops. Your real server would call listen(3000) and keep running.
ExampleNode.js
const http = require("http");
const todos = [];
let nextId = 1;
function send(res, status, data) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(data));
}
function handle(req, res) {
if (req.method === "GET" && req.url === "/todos") return send(res, 200, todos);
send(res, 404, { error: "Not found" });
}
// ---- demo: start on a free port, make a few requests, stop ----
const server = http.createServer(handle);
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const call = async (method, path, body) => {
const res = await fetch(base + path, { method, body: body ? JSON.stringify(body) : undefined });
const text = await res.text();
console.log(method, path, "->", res.status, text || "(empty)");
};
await call("GET", "/todos");
await call("GET", "/nothing-here");
server.close();
});Output
GET /todos -> 200 []
GET /nothing-here -> 404 {"error":"Not found"}The list is empty ([]) because nothing has been created yet, and an unknown URL gives a 404 with a JSON error message.
Quick check
What does the send helper avoid?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.