Skip to the workspace
Pebellslearn by building
The Server Half  ›  Lesson

A Node Server: Routes and Handlers

Node.js 14 minA Node.js server listens on a port and matches each request's method and path to a handler, which reads the request's params, query and body and sends exactly one response, with middleware running first for shared work.

full stack / A Node Server: Routes and Handlers

Explore each scene at your own pace.

01 · The rule

The rule

A Node Server: Routes and Handlers

At the other end of fetch('/api/plants') sits a Node.js program that has been waiting on a port. Its whole job is to read each request, pick the right piece of code for it, and send exactly one answer back. Sprout uses Express, the most common small web framework for Node, but every server framework follows the same shape.

The rule

A route is a method plus a path; its handler turns a request into a response.

import express from 'express';

const app = express();
app.use(express.json());                      // middleware: parse JSON bodies

app.get('/api/plants', async (req, res) => {
  const plants = await listPlants(req.user.id);
  res.json(plants);                           // 200 by default
});

app.post('/api/plants', async (req, res) => {
  const plant = await createPlant(req.user.id, req.body);
  res.status(201).json(plant);
});

app.listen(3000, () => console.log('Sprout API on port 3000'));
  • app.listen(3000) claims port 3000 and waits. Unlike a script, the process keeps running until it is stopped.
  • Routes. GET /api/plants and POST /api/plants share a path but are different routes, because the method differs.
  • req is the incoming request: req.params holds pieces of the path (/api/plants/:id), req.query holds the part after ?, req.body holds the parsed JSON, and headers and cookies are there too.
  • res is how you answer: choose a status, send a body. Every request needs exactly one response; a code path that sends none leaves the browser waiting until it gives up.
  • Middleware runs before handlers, for many routes at once: parsing JSON, logging, checking the login. It is registered with app.use, and order matters. JSON must be parsed before any handler reads req.body.

req.user is filled in by the login middleware you will meet in Section 4. For now, read it as "the person asking".

A single Node process can serve many users at once because handlers await slow work such as database queries. While one request waits for PostgreSQL, the process gets on with others.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.