Until now, the shop page drew its products from arrays written in app.js. A real shop keeps its products on a server, behind an API. The page reaches it at addresses that start with /api, like /api/products. The page's dev server passes every /api request on to the shop's API.
The browser's fetch function sends a request to an address. It does not wait for the answer: it returns a promise at once, a box that will hold the answer later. You give the promise a function with .then, and the promise calls it with the response when the answer arrives:
fetch("/api/categories")
.then((response) => {
console.log(response.ok);
});
This logs true when the status is in the 200s. response.status is the status code itself: a number like 200 (OK) or 404 (Not Found). The check prints every request the page makes and every console.log line, then the screen.
When the page opens, the check must print:
> open the page
request: GET /api/products -> 200
console.log: 200
screen:
…
text: 0 products
list (empty)
The list stays empty for now: you only look at the status, not at the products inside the answer. That is the next lesson.
Your task: at the end of app.js, ask for /api/products with fetch, and when the answer arrives, log its status with console.log.
Assignment
Follow the Coding Tutorial to send the page's first request with fetch and log the status of the answer.
Hint
Leave the semicolon off the fetch line: the .then on the next line goes on from it. The console.log goes inside the function you pass to .then.
Free plan: 30 tutor messages. PRO is unlimited.
