Start learning free

LESSON 17 OF 173 · BACKEND: YOUR FIRST API

When It Isn't There

Practice

When no product has the id that was asked for, the loop in the /products/:productId route ends without answering. Express doesn't answer for you: when your function sends nothing, the client keeps waiting for an answer that never comes. But nothing broke: the product just isn't there, and the API should say so.

The status code tells the client how its request went: 200 means OK, 404 means Not Found, 500 means the server failed. A plain res.json sends 200. To send another status, call res.status with the number, then .json right after it: the status first, then the body. For example, a members-only page could answer 403, which means Forbidden:

app.get("/vip", (req: Request, res: Response) => {
  res.status(403).json({ error: "Members only" });
});

An API answers its errors in JSON too, like {"error": "Product not found"}, so the client's program can read what went wrong. TypeScript sees the shape of the error object from its value, so there is no interface to write for it. The error belongs after the loop: those lines run only when no product matched.

Your app must answer:

GET /products/99    →  404  {"error": "Product not found"}
GET /products/2     →  200  {"id": 2, "name": "Notebook", "price": 7, "category": "office"}
GET /products/0     →  404  {"error": "Product not found"}
GET /products/5     →  404  {"error": "Product not found"}
GET /products/lamp  →  404  (an HTML error page)

Your task: after the loop in the /products/:productId route, make an object named error with the key error and the value "Product not found", and answer with it as JSON with the status 404.


Assignment
Follow the Coding Tutorial to answer 404 with a JSON error when no product has the requested id.


Hint
The two new lines go after the } that closes the for, not inside the loop. The status comes first: res.status with the number, then .json with the body.


STEP 1 OF 2
    Ctrl + Enter to check