Today's learning journey has taken me through the intricacies of using Axios, a promisted based HTTP client, for fetching data from public API using node.js. Here are the key notes for my own future reference:
- A promise is essentially a place holder for an operation that hs not been completed yet, allwoing for asynchronous execution.
- With Axios, I can chain up subsequent operations in .then() for successful reqeusts or handle errors in .catch(), while the rest of my code continues to run without waiting for the API response - this not only leads to a non-blocking code structure but also paves the way for more efficient and interactive web application.
Using Node's https module:
1 import https from "https"; 2 3 app.get("/", (req, res) => { 4 const options = { 5 hostname: "bored-api.appbrewery.com", 6 path: "/random", 7 method: "GET", 8 }; 9 10 const request = https.request(options, (response) => { 11 let data = ''; 12 response.on("data", (chunk) => { 13 data += chunk; 14 }); 15 16 response.on("end", () => { 17 try { 18 const result = JSON.parse(data); 19 res.render("index.ejs", {activity: data}); 20 } catch (error) { 21 console.error("Failed to parse response:", error.message); 22 res.status(500).send("Failed to fetch activity. Please try again."); 23 } 24 }); 25 }); 26 27 request.on("error", (error) => { 28 console.error("Failed to make request:", error.message); 29 res.status(500).send("Failed to fetch activity. Please try again."); 30 }); 31 32 request.end(); 33 });
Using axios:
import axios from "axios"; app.get("/", async (req, res) => { try { const response = await axios.get("https://bored-api.appbrewery.com/random"); res.render("index.ejs", { activity: response.data }); } catch (error) { console.error("Failed to make request:", error.message); res.status(500).send("Failed to fetch activity."); } });
Code Source: Udemy - The Complete 2023 Web Development Bootcamp by Angela Yu