Routing by Hand, and Why Frameworks Exist

A node:http server routes each request with if statements on its method and path, reads a JSON body that arrives in pieces, and grows a little with every address, which is the work a framework such as Express takes over.

Apprentice · Node.js · REST API · Updated

By

After this lesson you can

  • Route requests by hand with req.method and the URL's path, answering 404 for anything else
  • Read a JSON request body that arrives in chunks, answering 400 when it isn't valid JSON
  • Explain what a framework such as Express takes over, and why app.js and server.js are separate files

Key takeaways

  • Routing means choosing the code that answers a request from its method and its path. By hand, that's one if statement for each address, then a 404 for anything else.
  • A number in the path, such as the 3 in /tools/3, is text you split out of the path and turn into a number with Number().
  • A request body arrives in pieces, called chunks. for await collects them into text, and JSON.parse turns that text into data, or throws when it isn't valid JSON.
  • A framework such as Express takes over the repeated work, such as matching paths, reading bodies, sending JSON and answering 404, so each route is a few lines.
  • Keeping the request handler in app.js and the listen call in server.js lets tests use the handler without starting a server.

You'll build most APIs with a framework, starting with Express in Your First Express App: Routes and JSON. But you'll still meet plain node:http code: in small tools, in tests, and underneath every framework. Writing a few routes by hand once is the quickest way to see what a framework does for you, and why nearly every Node API uses one.

The garden also lends tools from its shed. The server from A Web Server with Node's http Module answers every request the same way, whatever the address, and the shed needs three answers: the list of tools at GET /tools, one tool at GET /tools/3, and borrowing one with POST /tools/3/borrow.

One if for each address

Choosing which code answers a request is called routing. By hand, it's an if for each address, called an endpoint: a method plus a path. Anything that matches no endpoint gets a 404. Since every answer needs writeHead and end, a small helper, sendJson, does both:

const tools = [
  { id: 1, name: "wheelbarrow", borrowedBy: null },
  { id: 2, name: "spade", borrowedBy: "Rosa" },
  { id: 3, name: "watering can", borrowedBy: null },
];

function sendJson(res, status, data) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data));
}
const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost:3100");

  if (req.method === "GET" && url.pathname === "/tools") {
    sendJson(res, 200, tools);
    return;
  }

  sendJson(res, 404, { message: `There's nothing at ${url.pathname}.` });
});

The return after each answer matters: without it, the code would carry on and answer a second time. GET /sprinklers gets the 404, its status line and body:

HTTP/1.1 404 Not Found

{"message":"There's nothing at /sprinklers."}

A number in the path

GET /tools/3 asks for one tool, and the 3 could be any id. split("/") cuts the path into its parts at each slash, and Number() turns the id's text into a number:

const url = new URL("/tools/3/borrow", "http://localhost:3100");
const parts = url.pathname.split("/");

console.log(parts);
console.log(Number(parts[2]));
console.log(Number("seven"));
[ '', 'tools', '3', 'borrow' ]
3
NaN

The path starts with a slash, so the first part is empty. NaN (read "not a number") is what Number gives for text that isn't a number, and no tool has that id. So one route, placed before the 404, covers every tool. find gives back the first tool its test says yes to, or undefined when none does:

  const parts = url.pathname.split("/");

  if (req.method === "GET" && parts.length === 3 && parts[1] === "tools") {
    const tool = tools.find((t) => t.id === Number(parts[2]));
    if (tool === undefined) {
      sendJson(res, 404, { message: `There's no tool ${parts[2]}.` });
      return;
    }
    sendJson(res, 200, tool);
    return;
  }

GET /tools/3 gets the watering can, and GET /tools/9 gets 404 with {"message":"There's no tool 9."}.

A request body arrives in pieces

Borrowing sends a body, { "neighbor": "Lena" }. A body doesn't arrive all at once: it comes over the network in pieces called chunks, and a big one comes in many. for await (a for...of loop that waits for each piece) collects them into text, and JSON.parse turns the text into data:

async function readJson(req) {
  let text = "";
  for await (const chunk of req) {
    text += chunk;
  }
  return JSON.parse(text);
}

When the text isn't valid JSON, JSON.parse throws, so the borrow route catches that and answers 400:

    let body;
    try {
      body = await readJson(req);
    } catch (error) {
      sendJson(res, 400, { message: "The body isn't valid JSON." });
      return;
    }
    tool.borrowedBy = body.neighbor;
    sendJson(res, 200, tool);

Lena's request gets {"id":3,"name":"watering can","borrowedBy":"Lena"}, and a body of { neighbor: Lena } (no quotes, so not JSON) gets 400 Bad Request.

The code that grows, and what a framework takes over

Three endpoints already fill about 60 lines, and every new one adds more of the same. A real shed would also want 409 for a tool that's already out, returning a tool, and checking the neighbor's name. A framework is ready-made code that runs your app and calls your code for the parts that differ. Express, the framework the next chapter starts with, takes over these jobs:

By hand With a framework such as Express
An if on the method and path for every endpoint One line names the method and path, such as /tools/:id (read "colon id")
Splitting the path and picking out the id The id arrives ready to read
readJson, chunks and try/catch for every body The body arrives as data
writeHead, JSON.stringify and end One call sends JSON
The 404 at the bottom, kept last Unmatched requests get a 404

app.js and server.js

One more change pays off as soon as you write tests. Keep the request handler in app.js and export it:

export async function app(req, res) {
  // the routes above, unchanged
}

server.js then only starts it:

import http from "node:http";
import { app } from "./app.js";

const server = http.createServer(app);

server.listen(3100, () => {
  console.log("Listening on http://localhost:3100");
});

A test can import app and hand it requests directly, with no server running and no port to choose. Testing an API with Supertest uses exactly that, and this chapter's exercise is already split this way.

Check yourself

2 questions to try on the lesson page.

So what

Every endpoint by hand costs an if, a split, a body reader and a 404, so when Express does those jobs in the next chapter, you'll know exactly what it saves you, and what's underneath when something goes wrong.

Key terms

Related