理解Asynchronous JavaScript:使用Axios获取数据
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器