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

Node.js调用API获取城市名报错:Cannot read property 'city_name' of undefined

解决 "Cannot read property 'city_name' of undefined" 错误

嘿,我来帮你拆解下这个问题的根源,以及对应的修复方案:

问题的核心原因

你碰到的错误主要来自两个关键问题:

  1. 没处理分块的响应数据:Node.js 里 https.get 的 data 事件是分批次触发的——API 返回的响应可能会被拆成多个 Buffer 块,你不能在每次 data 事件触发时就直接处理数据,得把所有块收集起来,等 end 事件触发时再统一处理。
  2. 没把 JSON 字符串转为 JS 对象:decoder.write(d) 返回的是 JSON 格式的字符串,不是能直接访问属性的 JavaScript 对象,必须用 JSON.parse() 转换成对象后,才能访问 data.city_name。

另外你当前代码里每次 data 事件都调用 decoder.write(d),这会导致解码器重复输出内容,因为 StringDecoder 会内部缓存未处理的数据,这种用法是不对的。

修复后的代码

我帮你调整了代码,解决了这些问题:

// 创建天气应用服务器
const express = require('express');
const app = express();
const https = require('https');

app.get('/', (req, res) => {
  const weatherPath = "https://api.weatherbit.io/v2.0/current?key=41c0f84d717a4764a26d144aa33a9443&city=melbourne,Australia"
  // 调用天气应用API
  https.get(weatherPath, (response) => {
    console.log(response.statusCode);
    
    // 收集所有响应数据块
    let responseData = '';
    
    // 每次拿到数据块,添加到收集变量中
    response.on('data', (d) => {
      responseData += d.toString('utf8'); // 直接把Buffer转成utf8字符串,无需额外的StringDecoder
    });
    
    // 所有数据接收完成后处理
    response.on('end', () => {
      try {
        // 把JSON字符串转为JS对象
        const weatherData = JSON.parse(responseData);
        // 注意:Weatherbit API的data是数组,要取第一个元素的city_name
        const cityName = weatherData.data[0].city_name;
        console.log(cityName);
      } catch (err) {
        console.error('解析JSON失败:', err);
      }
    });
    
    // 处理请求过程中的错误
    response.on('error', (err) => {
      console.error('请求API出错:', err);
    });
  });
  res.send("The server is up and running on the web");
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

额外补充说明

  • 我去掉了 StringDecoder,直接用 d.toString('utf8') 就能把 Buffer 转为 UTF8 字符串,更简洁高效。
  • 注意 Weatherbit 的 API 返回的 data 字段是一个数组,所以需要用 weatherData.data[0].city_name 来访问第一个天气对象的城市名,这也是你之前容易踩坑的点!
  • 加入了 try/catch 块处理 JSON 解析失败的情况,避免程序意外崩溃。
  • 添加了 error 事件监听,能捕获 API 请求过程中可能出现的网络错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:47:48