|
| 1 | +// 📌 JavaScript Intermediate - API Consumption (Fetch & Axios) |
| 2 | + |
| 3 | +// Welcome to the eighth section of the JavaScript Intermediate tutorial! |
| 4 | +// Here, you'll learn how to fetch data from APIs using Fetch API and Axios. |
| 5 | + |
| 6 | +// Define API URL for maintainability |
| 7 | +const API_URL = "https://jsonplaceholder.typicode.com/posts/1"; |
| 8 | + |
| 9 | +// Fetch API with Error Handling |
| 10 | +fetch(API_URL) |
| 11 | + .then((response) => { |
| 12 | + if (!response.ok) { |
| 13 | + throw new Error(`HTTP error! Status: ${response.status}`); |
| 14 | + } |
| 15 | + return response.json(); |
| 16 | + }) |
| 17 | + .then((data) => console.log("Fetch API Data:", data)) |
| 18 | + .catch((error) => console.error("Fetch Error:", error)); |
| 19 | + |
| 20 | +// Using Fetch with Async/Await and Error Handling |
| 21 | +async function getPost() { |
| 22 | + try { |
| 23 | + const response = await fetch(API_URL); |
| 24 | + if (!response.ok) { |
| 25 | + throw new Error(`HTTP error! Status: ${response.status}`); |
| 26 | + } |
| 27 | + const data = await response.json(); |
| 28 | + console.log("Async/Await Fetch Data:", data); |
| 29 | + } catch (error) { |
| 30 | + console.error("Error fetching post:", error); |
| 31 | + } |
| 32 | +} |
| 33 | +getPost(); |
| 34 | + |
| 35 | +// Using Axios (Ensure Axios is installed: npm install axios) |
| 36 | +import axios from "axios"; |
| 37 | + |
| 38 | +axios |
| 39 | + .get(API_URL) |
| 40 | + .then((response) => console.log("Axios Data:", response.data)) |
| 41 | + .catch((error) => { |
| 42 | + if (error.response) { |
| 43 | + console.error( |
| 44 | + `Axios Error: ${error.response.status} - ${error.response.statusText}` |
| 45 | + ); |
| 46 | + } else if (error.request) { |
| 47 | + console.error("Axios Error: No response received", error.request); |
| 48 | + } else { |
| 49 | + console.error("Axios Error:", error.message); |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | +// Axios with Async/Await and Error Handling |
| 54 | +async function getPostWithAxios() { |
| 55 | + try { |
| 56 | + const response = await axios.get(API_URL); |
| 57 | + console.log("Axios Async/Await Data:", response.data); |
| 58 | + } catch (error) { |
| 59 | + if (error.response) { |
| 60 | + console.error( |
| 61 | + `Axios Error: ${error.response.status} - ${error.response.statusText}` |
| 62 | + ); |
| 63 | + } else if (error.request) { |
| 64 | + console.error("Axios Error: No response received", error.request); |
| 65 | + } else { |
| 66 | + console.error("Axios Error:", error.message); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | +getPostWithAxios(); |
| 71 | + |
| 72 | +// 💡 Practice fetching data from different APIs using Fetch and Axios, and ensure proper error handling! |
0 commit comments