← Learning Hub
Intermediate

Express Basics: Routes and Parameters

Express is the most popular Node.js web framework. It makes routes, input and replies simple. Install it with npm install express.

Express is the most popular Node.js web framework because it's small and simple: you match addresses to handler functions and send replies. It handles the repetitive parts - parsing URLs, query strings, JSON responses - so you focus on your app.

Example
import express from "express";

const app = express();
const products = [
  { id: 1, name: "Kettle", price: 1299, category: "kitchen" },
  { id: 2, name: "Iron", price: 899, category: "home" },
  { id: 3, name: "Toaster", price: 1599, category: "kitchen" },
];

app.get("/", (req, res) => {
  res.send("Shop API is running");
});

// Query string: /products?category=kitchen&max=1500
app.get("/products", (req, res) => {
  let list = products;
  if (req.query.category) list = list.filter(p => p.category === req.query.category);
  if (req.query.max) list = list.filter(p => p.price <= Number(req.query.max));
  res.json(list);
});

// Route parameter: /products/2
app.get("/products/:id", (req, res) => {
  const p = products.find(x => x.id === Number(req.params.id));
  if (!p) return res.status(404).json({ error: "Product not found" });
  res.json(p);
});

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

// Start it with: node server.mjs
// Listening on http://localhost:3000
// Then try these requests (real replies):
// GET /
//   -> 200 Shop API is running
// GET /products?category=kitchen&max=1500
//   -> 200 [{"id":1,"name":"Kettle","price":1299,"category":"kitchen"}]
// GET /products/2
//   -> 200 {"id":2,"name":"Iron","price":899,"category":"home"}
// GET /products/99
//   -> 404 {"error":"Product not found"}

What's what

  • app.get(path, handler) - runs the handler for GET requests to that path (also post, put, patch, delete)
  • req.params - parts of the path like :id
  • req.query - the ?key=value part. Values are always strings, so convert numbers
  • res.json() sends JSON; res.status(404) sets the status code
Use return res.status(...).json(...) when you stop early, so the rest of the handler doesn't also try to reply.
Key points
  • app.get/post/... map routes to handlers.
  • req.params and req.query read input (as strings).
  • res.json and res.status send replies.

📝 Test yourself

1. Where do you find :id from /products/:id?
2. What type are req.query values?
3. Fill in the method that sends a JSON reply:
res.({ ok: true });