Fetch
What is fetch
fetch() is used to access resources across the network.
fetch accepts two parameters:
- resourceaccepts- URL stringor- Requestobject.
- optionsaccepts object with attributes like- method,- headers,- body.
const response = await fetch(resource[, options]);
Return Value
fetch() starts a request and returns a Promise.
- If the request fails due to network problems, the Promiseisrejected
- when the requestis complete, thePromiseis resolved with theResponseobject
Handling failed requests
fetch(request) .then((response) => { if (response.status === 200) { return response.json(); } else { throw new Error("response status is not 200, request failed"); } }) .then((response) => { console.debug(response); // … }) .catch((error) => { console.error(error); });