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

JS调用OpenWeatherMap天气API代码运行报错,请求协助排查修复

enter image description here

var path = "http://api.openweathermap.org/data/2.5/find?q=";
var city = "London";
var apiKey= "&appid=eb5eacd85411228f461a151003d9bf07";
var url = path + city+ apiKey;

function getTemp(){
fetch(url)
.then(response => response.json())
.then(data => {
  var nameValue= data.name;
  var tempr = data.main.temp;
  document.querySelector("h1").innerHTML= nameValue;
  document.querySelector("h2").innerHTML= tempr;
})}
getTemp();
代码核心问题
  • 混合内容拦截:请求使用http://协议,若运行页面为https://协议,浏览器会拦截跨域不安全请求,直接触发请求失败报错。
  • 接口与数据结构不匹配:/data/2.5/find为城市模糊搜索接口,返回结构为顶层包含list数组的结果集,不存在顶层name、main字段,直接读取对应属性会得到undefined值,渲染后不符合预期。
  • 缺失错误捕获逻辑:未校验fetch响应的状态码,也未设置catch捕获链路异常,遇到网络错误、接口权限报错时,无明确的问题定位提示。
  • 温度值可读性差:OpenWeatherMap接口默认返回开尔文单位的温度值,无单位转换时的数值不符合日常使用认知。
修复方案
  • 将请求协议替换为https://,避免跨协议拦截。
  • 更换为单城市查询专用的/data/2.5/weather接口,匹配单城市字段读取的逻辑。
  • 增加响应状态校验、全链路错误捕获逻辑,对异常场景做兜底提示。
  • 拼接URL时增加units=metric参数,直接获取摄氏度单位的温度值。

修复后的可运行代码:

const baseUrl = "https://api.openweathermap.org/data/2.5/weather?q=";
const city = "London";
// 完整拼接请求参数,包含单位配置、API密钥
const url = `${baseUrl}${city}&units=metric&appid=eb5eacd85411228f461a151003d9bf07`;

function getTemp(){
  fetch(url)
  .then(response => {
    // 拦截非成功状态的请求
    if (!response.ok) throw new Error(`接口请求异常,状态码:${response.status}`)
    return response.json()
  })
  .then(data => {
    const cityName = data.name;
    const temp = data.main.temp;
    document.querySelector("h1").textContent = cityName;
    // 温度值附加单位,提升可读性
    document.querySelector("h2").textContent = `${temp}℃`;
  })
  .catch(err => {
    console.error("天气数据加载失败:", err.message)
  })
}
getTemp();

注意:修改后的代码使用textContent做DOM内容写入,相比innerHTML可避免潜在的XSS注入风险。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 03:57:03