Fetch API & Errors in JavaScript
The fetch API, as the name implies, is used to get data from APIs. It is a browser API that allows you to use JavaScript to make basic AJAX (Asynchronous JavaScript and XML) requests.
Because it is given by the browser, you may use it without having to install or import any packages or dependencies (like Axios). Its configuration is fairly simple to grasp.
Let’s see how to fetch data via the fetch API. We'll use a free API that contains thousands of random quotes:
fetch("https://type.fit/api/quotes").then((response) => response.json()).then((data) => console.log(data)).catch((err) => console.log(err));
What we did here was:
- Line 1: we got the data from the API, which returned a promise
- Line 2: We then got the .json() format of the data which is also a promise
- Line 3: We got our data which now returns JSON
- Line 4: We got the errors in case there are any
Post a Comment