Node.js读取外部网站API的JSON数据及定时轮询功能实现求助
问题原因
fs是Node.js内置的本地文件系统操作模块,仅支持读取本机磁盘上的文件,无法处理HTTP/HTTPS协议的外部网站地址,所以原有方案会报错。
可用修复方案
以下提供两种可直接运行的实现,均已包含5分钟自动刷新逻辑,且首次运行会立即返回结果无需等待5分钟:
方案1:使用Node.js内置模块(无需安装第三方依赖)
如果请求地址是HTTP协议,将代码中的require("https")改为require("http")即可
const https = require("https"); // 替换为你实际要请求的外部JSON地址 const JSON_URL = "https://你要请求的json地址"; // 封装JSON请求逻辑 function fetchJsonResult() { https.get(JSON_URL, (res) => { let jsonString = ""; // 拼接返回的数据流片段 res.on("data", (chunk) => { jsonString += chunk; }); // 数据接收完成后处理 res.on("end", () => { try { const useroutput = JSON.parse(jsonString); console.log("Customer address is:", useroutput.result); } catch (err) { console.log("Error parsing JSON string:", err); } }); }).on("error", (err) => { console.log("Error requesting JSON:", err); }); } // 首次运行立即请求一次 fetchJsonResult(); // 设置5分钟(300000毫秒)定时刷新 setInterval(fetchJsonResult, 5 * 60 * 1000);
方案2:使用第三方axios包(代码更简洁)
先执行npm i axios安装依赖后使用:
const axios = require("axios"); // 替换为你实际要请求的外部JSON地址 const JSON_URL = "https://你要请求的json地址"; async function fetchJsonResult() { try { const { data: useroutput } = await axios.get(JSON_URL); console.log("Customer address is:", useroutput.result); } catch (err) { console.log("Request or parse error:", err); } } // 首次运行立即请求一次 fetchJsonResult(); // 设置5分钟定时刷新 setInterval(fetchJsonResult, 5 * 60 * 1000);
注意事项
- 如果目标站点有反爬限制,可以在请求头中添加
User-Agent等常规浏览器字段即可正常请求 - 若请求返回的不是标准JSON格式,可打印返回的原始字符串排查格式问题
内容的提问来源于stack exchange,提问作者val
相关产品推荐
相关产品推荐

