Node.js使用requests包从API获取数据并替换HTML内容无输出问题排查
问题分析与解决方案
我一眼就看到问题所在啦——页面没输出、mainData是空字符串,核心原因是**map回调函数里没有返回值**,导致映射后的数组全是undefined,join之后自然成了空串。下面一步步给你修正:
1. 修复map的返回值问题
你的replaceVal函数是有返回结果的,但在arrData.map里调用它时,没把结果返回出去。修改这部分代码:
const mainData = arrData .map((val) => { // 必须return替换后的模板内容! return replaceVal(mainFile, val); }) .join("");
或者用更简洁的箭头函数写法:
const mainData = arrData .map(val => replaceVal(mainFile, val)) .join("");
2. 检查API请求的城市名称
你请求的城市是q=wah,这个名称大概率不存在或者拼写错误,OpenWeatherMap会返回错误数据,导致后续解析出问题。建议换成确定存在的城市,比如q=London或者你所在的城市名。
3. 扩展模板替换逻辑(可选优化)
当前replaceVal只替换了温度,你可以扩展它替换更多内容,比如城市和国家:
const replaceVal = (oldval, newval) => { let temp = oldval.replace("City,Country", `${newval.name}, ${newval.sys.country}`); temp = temp.replace("Tempracture", `${newval.main.temp}°C`); return temp; };
这样HTML里的两个占位符都能被正确替换。
4. 解决静态资源(CSS)的访问问题
你的服务器现在只处理了/路径的请求,浏览器请求style.css时会返回404,导致CSS不生效。可以添加分支处理静态资源:
if (req.url == "/") { // 原有的API请求和页面渲染逻辑 } else if (req.url == "/style.css") { fs.readFile("style.css", "utf-8", (err, data) => { if (err) { res.writeHead(404); res.end("CSS文件未找到"); return; } res.writeHead(200, {"Content-Type": "text/css"}); res.end(data); }); } else { res.writeHead(404); res.end("页面未找到"); }
完整修正后的后端代码
const fs = require("fs"); const http = require("http"); let requests = require("requests"); const mainFile = fs.readFileSync("index.html", "utf-8"); const replaceVal = (oldval, newval) => { let temp = oldval.replace("City,Country", `${newval.name}, ${newval.sys.country}`); temp = temp.replace("Tempracture", `${newval.main.temp}°C`); return temp; }; const server = http.createServer((req, res) => { if (req.url == "/") { requests( "https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=8b949ed0b4efff029e789ed12aab16a0" ) .on("data", (cdata) => { const objData = JSON.parse(cdata); const arrData = [objData]; const mainData = arrData .map(val => replaceVal(mainFile, val)) .join(""); res.write(mainData); console.log(mainData); }) .on("end", (err) => { if (err) return console.log("请求错误:", err); res.end(); }); } else if (req.url == "/style.css") { fs.readFile("style.css", "utf-8", (err, data) => { if (err) { res.writeHead(404); res.end("CSS文件未找到"); return; } res.writeHead(200, {"Content-Type": "text/css"}); res.end(data); }); } else { res.writeHead(404); res.end("页面未找到"); } }); server.listen(3000, "127.0.0.1", () => { console.log("服务器已启动,监听http://127.0.0.1:3000"); });
现在运行代码,访问http://127.0.0.1:3000就能看到替换后的温度和城市信息,CSS也会正常加载啦~
内容的提问来源于stack exchange,提问作者Dev Hamza
相关产品推荐
相关产品推荐

