Sikau

Node.js · Day 9 · about 30 min

Express basics

Routes, params, queries and JSON — cleanly.

The same API, half the code

Express is the most used Node web framework. It gives you app.get("/dishes/:id", handler), parsed query strings and bodies, and helpers like res.json() — so routes read like a table of contents.

app.get, req.params, req.query, res.json

import express from "express";

const app = express();
const dishes = [
  { id: 1, name: "Momo", price: 180, veg: false },
  { id: 2, name: "Veg momo", price: 160, veg: true },
];

app.get("/", (req, res) => {
  res.send("Welcome to the café API");
});

app.get("/dishes", (req, res) => {
  const list = req.query.veg === "true" ? dishes.filter((d) => d.veg) : dishes;
  res.json(list);
});

app.get("/dishes/:id", (req, res) => {
  const dish = dishes.find((d) => d.id === Number(req.params.id));
  if (!dish) return res.status(404).json({ error: "Dish not found" });
  res.json(dish);
});

app.listen(3000, () => console.log("API on http://localhost:3000"));

console.log(await (await fetch("http://localhost:3000/dishes?veg=true")).json());
console.log(await (await fetch("http://localhost:3000/dishes/1")).json());
console.log((await fetch("http://localhost:3000/dishes/9")).status);
  • Routes are checked top to bottom; the first match handles the request.
  • res.send() for text/HTML, res.json() for JSON, res.sendStatus(204) for no content.
  • Unmatched routes get Express's default 404 ("Cannot GET /x").

The rest of this lesson

  • Route parameters and query stringsexplain
  • Order and specificityexplain
  • What's req.params.id?predict
  • Which route wins?predict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js