You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Openweather API获取的数据传递到自行设计的HTML页面

问题根因与修复方案

核心错误说明

  • 你混淆了服务端代码和浏览器端代码的运行环境:document是浏览器提供的DOM对象,只能在用户浏览器加载的前端JS里调用,你写在Express服务端代码里根本不存在这个对象,自然没办法修改HTML内容
  • 你在调用res.sendFile之后才去请求OpenWeather接口,此时HTML已经提前返回给用户浏览器了,后续服务端的操作和用户前端已经没有关联
  • 注意Express的res.sendFile是驼峰命名,你代码里写的小写res.sendfile在高版本Express中可能报错,建议统一修改为驼峰写法

修复步骤

第一步:修改服务端POST接口逻辑

不要直接返回静态HTML,改为请求完天气接口后返回JSON数据:

// 把原来的app.post("/weatherdata")替换成下面的代码
app.post("/weatherdata", (req, res) => {
  const cityname = req.body.cityName;
  const apiid = "b75642448cbd207923a63b89cf48768d";
  // 加units=metric参数直接返回摄氏度,无需后续自行转换单位
  const url = `http://api.openweathermap.org/data/2.5/weather?q=${cityname}&appid=${apiid}&units=metric`;

  http.get(url, (apiRes) => {
    let rawData = '';
    apiRes.on('data', (chunk) => { rawData += chunk; });
    apiRes.on('end', () => {
      try {
        const weatherData = JSON.parse(rawData);
        // 返回JSON数据给前端
        res.json({
          code: 200,
          temp: weatherData.main.temp,
          city: weatherData.name
        });
      } catch (e) {
        res.json({code: 500, msg: '天气数据解析失败'});
      }
    });
  }).on('error', (e) => {
    res.json({code: 500, msg: '天气接口请求失败'});
  });
})

第二步:在前端weatherData.html中添加交互逻辑

在HTML页面内写前端JS,监听表单提交事件,调用后台接口拿到数据后再操作DOM更新页面:

<!-- 把这段代码加在weatherData.html的</body>闭合标签之前 -->
<script>
// 假设你页面内提交城市的表单id为weatherForm,城市输入框name属性为cityName,可根据实际情况修改选择器
document.querySelector('#weatherForm').addEventListener('submit', function(e) {
  e.preventDefault(); // 阻止表单默认跳转提交行为
  const cityName = document.querySelector('input[name="cityName"]').value;
  
  // 调用后台接口拿天气数据
  fetch('/weatherdata', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `cityName=${encodeURIComponent(cityName)}`
  })
  .then(res => res.json())
  .then(data => {
    if(data.code === 200) {
      // 拿到温度后更新DOM
      document.querySelector(".main-degree").innerHTML = `${data.temp} °C`;
    } else {
      alert(data.msg);
    }
  })
})
</script>

第三步:保留原有静态页面路由

原来的GET /weatherdata接口无需修改,正常返回静态HTML页面即可,用户打开页面后提交表单会自行触发前端JS请求数据渲染。

内容的提问来源于stack exchange,提问作者Vivek Akepogu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:00:00