调用OpenWeather API时触发TypeError:Cannot read property 'temp' of undefined
问题解答
一、OpenWeather Forecast接口调用错误修复
你遇到的TypeError: Cannot read property 'temp' of undefined有两个核心原因:
1. 接口返回结构不匹配
Forecast(天气预报)接口的返回结构和实时天气接口不同,它的main对象并非直接挂载在根节点下,而是嵌套在list数组的每个元素里。典型返回结构如下:
{ "list": [ { "main": { "temp": 25.6 // ...其他天气字段 }, // ...后续时段的天气数据 } ] }
直接取weatherData.main必然会得到undefined,需要从list数组中选取对应时段的main.temp。
2. HTTP数据接收方式错误
Node.js的https.get的data事件会分多次触发,每次仅返回部分数据块,直接在这个事件里解析JSON会导致数据不完整或报错。正确做法是把所有数据块拼接起来,在end事件(数据接收完成)中再解析。
修复后的代码
const express = require("express"); const https = require("https"); const app = express(); app.get("/", function (req, res) { const url = "https://api.openweathermap.org/data/2.5/forecast?q=delhi&appid={apikey}&units=metric"; https.get(url, function (response) { console.log(response.statusCode); let rawData = ''; // 拼接所有数据块 response.on("data", function(chunk){ rawData += chunk; }); // 数据接收完成后解析并取值 response.on("end", function(){ const weatherData = JSON.parse(rawData); // 取第一个时段的温度,也可遍历list获取所有时段数据 const firstTemp = weatherData.list[0].main.temp; console.log(firstTemp); }); }); res.send("server is up"); }); app.listen(3000, function () { console.log("server is running"); });
二、Stack Overflow发帖流程为何繁琐?
Stack Overflow的流程设计核心是过滤低质量提问,确保每个问题具备清晰性、可复现性,让其他开发者能快速理解并给出有效解答:
- 强制精准标题,避免模糊表述;
- 要求格式化代码、明确报错信息,降低理解成本;
- 引导添加合适标签,让领域内开发者快速定位问题;
- 督促用户先自查,减少重复提问。
看似繁琐的流程,实则是为了维护社区内容质量,减少无效提问,让真正有价值的问题更快得到解决方案。
内容的提问来源于stack exchange,提问作者Akshat Sharma
相关产品推荐
相关产品推荐

