如何将OpenWeather API获取的天气数据传递至HTML页面并默认展示多伦多天气
现有代码存在的核心问题
- 异步时序逻辑错误:OpenWeather的
https.get请求是异步执行的,response.on("data")事件是分块接收接口响应的,你在分块事件里直接做JSON解析、调用res.write的同时,还同步执行res.sendFile,既会因为分块数据不完整导致JSON.parse失败,还会因为重复设置HTTP响应头触发Cannot set headers after they are sent的运行时报错。 - 响应逻辑冲突:同一个HTTP响应对象不能既通过res.write拼接自定义内容,又调用res.sendFile返回本地静态文件,二者的响应流是互斥的。
- 请求参数错误:你写的OpenWeather请求URL里
q=Toronto后面带了多余空格,会导致城市参数识别失败,返回接口报错。
两种可实现需求的方案(全程使用GET请求,无需POST)
方案1:服务端渲染替换(最贴近你现有代码的改造方式)
在Node服务端接收完整的OpenWeather接口数据后,把数据直接替换到本地HTML的占位符位置,再把渲染完成的HTML返回给用户,整个过程不依赖前端额外发请求。
- 预先改造本地
index.html,加入占位符结构:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>多伦多实时天气</title> </head> <body> <p>当前天气状况:<span id="weather-desc">{{WEATHER_DESC}}</span></p> <h1>多伦多当前气温:<span id="TEMP_PLACEHOLDER"></span> 摄氏度</h1> <img id="weather-icon" src="{{ICON_URL}}" alt="天气图标"> </body> </html>
- 改造Node端的路由逻辑:
const https = require('https'); const fs = require('fs'); const path = require('path'); app.get("/", function(req, res) { // 移除URL中Toronto后的多余空格,替换成自己的真实API Key const weatherApiUrl = "https://api.openweathermap.org/data/2.5/weather?q=Toronto&appid=你的实际API密钥&units=metric"; https.get(weatherApiUrl, function(apiResponse) { let fullResponseData = ''; // 分块拼接接口返回的原始数据 apiResponse.on('data', chunk => fullResponseData += chunk); // 等接口数据完全接收后再做解析 apiResponse.on('end', function() { const weatherData = JSON.parse(fullResponseData); const temp = weatherData.main.temp; // 修正原代码的拼写错误:describtion -> description const description = weatherData.weather[0].description; const iconId = weatherData.weather[0].icon; const imgURL = `http://openweathermap.org/img/wn/${iconId}@2x.png`; // 读取本地HTML文件内容 fs.readFile(path.join(__dirname, 'index.html'), 'utf8', function(readErr, htmlContent) { if (readErr) return res.status(500).send('页面加载异常'); // 替换HTML中的占位符为真实天气数据 const finalHtml = htmlContent .replace('{{WEATHER_DESC}}', description) .replace('TEMP_PLACEHOLDER', temp) .replace('{{ICON_URL}}', imgURL); // 返回渲染完成的HTML res.send(finalHtml); }); }); }).on('requestError', () => { res.status(500).send('天气数据获取失败'); }); });
方案2:前后端分离接口传值(更易维护的实现方式)
服务端拆分职责:一个路由负责返回静态HTML页面,另一个独立的GET接口负责返回结构化的天气JSON数据,HTML加载完成后由内嵌JS请求接口、把数据渲染到页面元素上。
- Node端路由拆分:
const https = require('https'); const path = require('path'); // 根路由仅负责返回静态HTML页面 app.get("/", function(req, res) { res.sendFile(path.join(__dirname, "/index.html")); }); // 新增独立GET接口,返回结构化天气数据 app.get("/api/weather/toronto", function(req, res) { const weatherApiUrl = "https://api.openweathermap.org/data/2.5/weather?q=Toronto&appid=你的实际API密钥&units=metric"; https.get(weatherApiUrl, function(apiResponse) { let rawData = ''; apiResponse.on('data', chunk => rawData += chunk); apiResponse.on('end', () => { const weatherData = JSON.parse(rawData); // 整理需要的字段为JSON返回 res.json({ temp: weatherData.main.temp, description: weatherData.weather[0].description, imgURL: `http://openweathermap.org/img/wn/${weatherData.weather[0].icon}@2x.png` }); }); }).on('error', () => res.status(500).json({msg: "天气获取失败"})); });
- 在
index.html中加入内嵌渲染逻辑:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>多伦多实时天气</title> </head> <body> <p>当前天气状况:<span id="weather-desc"></span></p> <h1>多伦多当前气温:<span id="temp-value"></span> 摄氏度</h1> <img id="weather-icon" src="" alt="天气图标"> <script> // 页面DOM加载完成后请求天气接口 document.addEventListener('DOMContentLoaded', async () => { const apiRes = await fetch('/api/weather/toronto'); const weatherInfo = await apiRes.json(); // 把接口拿到的数据填充到对应DOM元素 document.querySelector('#weather-desc').textContent = weatherInfo.description; document.querySelector('#temp-value').textContent = weatherInfo.temp; document.querySelector('#weather-icon').src = weatherInfo.imgURL; }) </script> </body> </html>
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

