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

Node.js+fetch无法将API数据渲染到HTML?求正确实现方式

问题根源

Node.js是服务器端运行环境,它本身没有浏览器的DOM API(比如document.getElementById这类操作页面元素的方法)。你用node-fetch能在控制台输出数据,是因为Node.js可以发起HTTP请求获取数据,但它没法直接修改客户端的HTML页面——这就是代码仅能控制台输出、无法渲染页面的核心原因。

两种正确实现方案

方案1:服务器端渲染(SSR),直接把数据注入HTML

用Express搭建简单服务器,在服务器端获取天气数据后,将数据嵌入HTML模板再返回给浏览器。

步骤示例

  1. 安装依赖:
npm install express node-fetch
  1. 编写服务器代码(server.js):
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const PORT = 3000;

// OpenWeatherMap 配置
const API_KEY = '你的API密钥';
const CITY = 'Beijing';

app.get('/', async (req, res) => {
  try {
    // 服务器端请求天气数据
    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${CITY}&appid=${API_KEY}&units=metric`);
    const weatherData = await response.json();

    // 构造带数据的HTML内容(复杂场景可改用EJS、Pug等模板引擎)
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <title>实时天气</title>
        <style>table {border-collapse: collapse;} th,td {border:1px solid #ccc; padding:8px;}</style>
      </head>
      <body>
        <h1>${CITY} 天气信息</h1>
        <table>
          <tr><th>温度</th><td>${weatherData.main.temp} ℃</td></tr>
          <tr><th>湿度</th><td>${weatherData.main.humidity} %</td></tr>
          <tr><th>天气状况</th><td>${weatherData.weather[0].description}</td></tr>
        </table>
      </body>
      </html>
    `;
    res.send(html);
  } catch (error) {
    res.send(`数据获取失败:${error.message}`);
  }
});

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
  1. 启动服务器:node server.js,访问http://localhost:3000即可看到渲染好的页面。

方案2:Node.js做API接口,前端页面fetch获取数据

让Node.js仅负责提供天气数据的API接口,前端页面用浏览器原生fetch请求该接口,再完成页面渲染。

步骤示例

  1. 安装依赖后,编写服务器代码(server.js):
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const PORT = 3000;

const API_KEY = '你的API密钥';

// 开放天气数据API接口
app.get('/api/weather', async (req, res) => {
  const city = req.query.city || 'Beijing';
  try {
    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
    const weatherData = await response.json();
    res.json(weatherData);
  } catch (error) {
    res.status(500).json({error: error.message});
  }
});

// 托管静态页面(将你的index.html放在public文件夹下)
app.use(express.static('public'));

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
  1. 新建public文件夹,放入index.html:
<!DOCTYPE html>
<html>
<head>
  <title>天气查询</title>
  <style>table {border-collapse: collapse;} th,td {border:1px solid #ccc; padding:8px;}</style>
</head>
<body>
  <h1>天气查询</h1>
  <div id="weather-container"></div>
  <script>
    async function loadWeather() {
      try {
        const response = await fetch('/api/weather?city=Beijing');
        const data = await response.json();
        const table = `
          <table>
            <tr><th>温度</th><td>${data.main.temp} ℃</td></tr>
            <tr><th>湿度</th><td>${data.main.humidity} %</td></tr>
            <tr><th>天气状况</th><td>${data.weather[0].description}</td></tr>
          </table>
        `;
        document.getElementById('weather-container').innerHTML = table;
      } catch (error) {
        document.getElementById('weather-container').innerHTML = `数据获取失败:${error.message}`;
      }
    }
    // 页面加载时触发数据获取
    window.onload = loadWeather;
  </script>
</body>
</html>
  1. 启动服务器后访问http://localhost:3000,前端会自动请求接口并渲染数据。
原有代码问题排查

如果你的原有Node.js代码里写了document.getElementById('xxx').innerHTML = ...这类操作DOM的代码,必然无效——Node.js环境不存在document对象。你需要明确:Node.js负责服务器端的数据获取与接口提供,页面渲染是浏览器端的工作,两者通过HTTP请求完成交互。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:16:06