In-Class Node JS Exercise 3

Exercise · Fix This Express Route

Node.js · Express · Debugging
The route has a bug. Explain the problem, fix the code, and explain your solution out loud.
const express = require("express");
const app = express();

app.use(express.json());

const users = [
    { id: 1, name: "Anna" },
    { id: 2, name: "Ben" },
    { id: 3, name: "Carlos" }
];

app.get("/users/:id", (req, res) => {
    const user = users.find(user => user.id === req.params.id);

    if (!user) {
        res.status(404).json({ message: "User not found" });
    }

    res.json(user);
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});
🎯 Instructions debugging task
  1. Explain what the route is supposed to do.
  2. Find the bug in the comparison.
  3. Explain why req.params.id causes a problem.
  4. Fix the type mismatch.
  5. Find the second bug after the 404 response.
  6. Add a return statement.
  7. Explain the corrected code.
📖 Vocabulary core
  • route parameter — a dynamic value in a URL.
  • type mismatch — when two values have different data types.
  • array — a list of values.
  • find — an array method that returns the first matching item.
  • JSON — a common data format for APIs.
  • bug — a mistake in the code.
🧩 Collocations natural English
  • define a route
  • extract a parameter
  • convert a string to a number
  • search an array
  • return a JSON response
  • fix a bug
🗣️ Phrasal Verbs interview speech
  • look up — "The route looks up a user by ID."
  • run into — "We run into a type mismatch problem."
  • turn into — "We need to turn the string ID into a number."
  • stop from — "The return statement stops the function from sending two responses."
✅ Fixed Code solution
app.get("/users/:id", (req, res) => {
    const userId = Number(req.params.id);

    const user = users.find(user => user.id === userId);

    if (!user) {
        return res.status(404).json({ message: "User not found" });
    }

    res.json(user);
});
🎤 Model Answer spoken

This Express route is supposed to find one user by ID.

The ID comes from the URL parameter req.params.id. However, route parameters are strings by default. In the users array, the IDs are numbers.

The original code compares a number to a string using strict equality, so the comparison fails.

To fix this, we convert req.params.id into a number using Number().

There is also another issue. If no user is found, the route sends a 404 response, but the function continues and tries to send another response with res.json(user).

We fix that by adding return before the 404 response. This stops the function immediately.