使用Fetch API调用Met Office Data Point API显示经纬度失败求助
问题排查与修正方案
核心问题分析
- API返回结构不匹配:Met Office Data Point的站点列表接口返回的JSON并非直接数组,实际站点数据嵌套在
Locations.Location路径下。你之前直接对顶层对象调用forEach,自然无法遍历数据。 - 潜在的协议问题:原URL使用
http,部分浏览器会拦截混合内容(页面用https加载但请求http资源),建议改用https协议。
修正后的完整代码
JavaScript部分
async function getLocations() { // 改用https协议,避免混合内容拦截 let url = 'https://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/sitelist?key=231f9773-2c4f-4afd-beee-6878c1c63f0a'; try { let res = await fetch(url); // 检查响应是否成功,避免解析错误状态的JSON if (!res.ok) { throw new Error(`请求失败,状态码: ${res.status}`); } return await res.json(); } catch (error) { console.error('获取站点数据出错:', error); return null; // 返回null防止后续代码崩溃 } } async function renderLocations() { let locationData = await getLocations(); // 校验数据结构,防止API返回格式异常 if (!locationData?.Locations?.Location) { console.error('数据格式不符合预期'); return; } // 取出实际的站点数组 let locations = locationData.Locations.Location; let html = ''; locations.forEach(location => { // 明确标注经纬度,提升可读性 let htmlSegment = `<div class="Location"> <h2>经度: ${location.longitude},纬度: ${location.latitude}</h2> </div>`; html += htmlSegment; }); let container = document.querySelector('.container'); if (container) { container.innerHTML = html; } else { console.error('页面中未找到.container容器'); } } renderLocations();
HTML部分
<div class="container"></div>
额外优化说明
- 增加了响应状态检查,能及时捕获API请求失败的情况
- 加入数据结构校验,避免因API返回格式变化导致代码报错
- 调整了经纬度的展示文本,让页面内容更易读
- 改用https协议,确保请求在现代浏览器中正常执行
内容的提问来源于stack exchange,提问作者mblack204
相关产品推荐
相关产品推荐

