Start learning free

LESSON 4 OF 173 · BACKEND: HOW THE WEB WORKS

Check the Status First in TypeScript

Practice

Every answer from a server starts with a status code: a number that says how the request went. 200 OK means the body holds what you asked for. 404 Not Found means there is nothing at that address. A 404 is not a crash: the request went out, and the server answered.

The status tells you what the body holds, so check it before you use the body. Here is the idea on another page of the supplier:

const response = await fetch(SUPPLIER + "/catalog?page=1");
if (response.status === 200) {
  console.log("Got the page");
}

Your script looks up three product ids: 3, 99 and 5. The supplier has no product 99, so it answers 404, and its body holds an error instead of a product. as Product only tells TypeScript what shape to expect; it checks nothing when the script runs. Reading .name from the 404 body gives undefined, so the script would print undefined costs undefined as if nothing were wrong.

GET /prices/3   →  200  {"name": "Lamp", "price": 14, …}
GET /prices/99  →  404  {"error": "No product with that id"}
GET /prices/5   →  200  {"name": "Plant", "price": 6, …}

Your script must print:

Product 3 - status 200
Lamp costs 14
Product 99 - status 404
No such product at the supplier
Product 5 - status 200
Plant costs 6

Your task: loop over productIds, fetch /prices/ followed by each id, and print the id and its status code. For a 200, read the JSON as Product and print the product's name, "costs" and its price. For a 404, print "No such product at the supplier".


Assignment
Follow the Coding Tutorial to request each product, print its status code and handle the 200 and 404 answers.


Hint
The id is a number, but + turns it into text when it joins it to the address, and TypeScript allows that. Put await before fetch and before response.json(), and add as Product after the JSON. Print the status before the if, and start the else if right after the if's closing }.


STEP 1 OF 8
    Ctrl + Enter to check

    Web Status Codes in TypeScript

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free