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

使用Vanilla JS调用Weatherbit Rapid API时'temp'读取错误求助

问题排查与解决

错误原因分析

报错Cannot read properties of undefined (reading 'temp')是因为你直接从返回的data对象中读取temp,但Weatherbit的3小时预报API返回结构里,temp并不在顶层data对象中,而是嵌套在data.data数组的子对象里;同时DOM操作也存在两处问题。

具体修复步骤

1. 修正API数据读取路径

Weatherbit的forecast/3hourly接口返回的JSON结构大致如下:

{
  "data": [
    {
      "temp": 22.5,
      // 其他字段...
    },
    // 更多时段数据...
  ],
  // 其他顶层字段...
}

你需要从data.data数组中取对应时段的温度,比如第一个时段的温度:data.data[0].temp

2. 修复DOM元素获取与赋值错误

  • document.getElementsByClassName('temp')返回的是HTMLCollection类数组对象,不是单个DOM元素,需要通过索引获取第一个元素(比如tempValue[0]),或者改用document.querySelector('.temp')直接获取单个元素更简洁。
  • 赋值时的innerHtml是拼写错误,正确写法是innerHTML(注意大写的H)

修正后的完整代码

// 改用querySelector获取单个元素,更直观
const tempValue = document.querySelector('.temp')

const options = {
  method: 'GET',
  headers: {
    'X-RapidAPI-Key': '************************************',
    'X-RapidAPI-Host': 'weatherbit-v1-mashape.p.rapidapi.com'
  }
}

document.getElementById('submit').addEventListener('click', e => {
  e.preventDefault()

  fetch(
      'https://weatherbit-v1-mashape.p.rapidapi.com/forecast/3hourly?lat=35.5&lon=-78.5',
      options
    )
    .then(response => response.json())
    .then(data => {
      // 取第一个时段的温度
      let tempval = data.data[0].temp
      // 修正拼写错误的innerHTML
      tempValue.innerHTML = tempval
    })
    .catch(err => console.error(err))
})

额外建议

  • 可以在.then(data => {})里先执行console.log(data),查看完整的API返回结构,确认字段位置是否正确。
  • 如果需要显示其他时段的温度,可以遍历data.data数组来处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:55:16