无法将Prompt获取的GPS坐标传入OpenWeatherMap API获取天气数据求助
问题分析与修复方案
你的代码无法获取API数据的核心原因是fetch请求的URL拼接语法错误,字符串与变量之间未使用正确的连接方式,导致浏览器解析失败,请求根本无法发送。以下是详细问题点及修复方案:
1. 核心错误:URL拼接语法问题
错误写法中直接将字符串和Number(firstnumber)拼接,未使用+或模板字符串连接,导致语法报错:
// 错误写法 const meteo = await fetch('https://api.openweathermap.org/data/2.5/weather?lat='Number(firstnumber)'&lon='Number(secondnumber)'&units=metric&lang=fr&appid=XXX')
修复方式:使用模板字符串(反引号`)拼接,更清晰且不易出错:
// 正确写法 const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${Number(firstnumber)}&lon=${Number(secondnumber)}&units=metric&lang=fr&appid=XXX`)
2. 其他需要修复的问题
重复的根HTML标签
代码开头存在两个<html>标签,需删除第二个<html>,保留<html lang="en">以保证HTML结构有效性。
缺少请求错误处理
未处理网络失败、API返回错误(如密钥无效、坐标非法)等情况,添加try/catch块可捕获并排查问题:
async function main(){ try { const response = await fetch(`API_URL`); if (!response.ok) { throw new Error(`API请求失败:${response.status}`); } const meteo = await response.json(); displayWeatherInfos(meteo); } catch (error) { console.error('获取天气数据失败:', error); alert('无法获取数据,请检查输入或网络'); } }
输入验证缺失
用户可能输入非数字内容,导致API请求无效,需添加输入验证:
let firstnumber, secondnumber; // 验证纬度输入 do { firstnumber = prompt("entrez la latitude (十进制,例如48.8566)"); } while (isNaN(Number(firstnumber)) || firstnumber === null); // 验证经度输入 do { secondnumber = prompt("entrez la longitude (十进制,例如2.3522)"); } while (isNaN(Number(secondnumber)) || secondnumber === null);
日期格式化错误
toUTCString(sunrise*1000)写法错误(toUTCString无需参数),若需显示本地时区时间,推荐使用法语适配的格式化方法:
document.querySelector('#sunrise').textContent = new Date(sunrise*1000).toLocaleTimeString('fr-FR'); document.querySelector('#sunset').textContent = new Date(sunset*1000).toLocaleTimeString('fr-FR');
完整修复后代码
<html lang="en"> <head> <title>API METEO</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> </head> <body> <h2>METEO</h2> <h2> <span id='temperature'>"temperature"</span> c° (temperature) </h2> <h2> <span id='pressure'>"pressure"</span> hpa (pression par rapport au niveau de la mer) </h2> <h2> <span id='visibility'>"visibility"</span> km (visibilité horizontale) </h2> <h2> <span id='windspeed'>"windspeed"</span> km/h (vitesse du vent) </h2> <h2> <span id='winddire'>"winddire"</span> ° (direction du vent) </h2> <h2> <span id='clouds'>"clouds"</span> % (couverture nuageuse) </h2> <h2> <span id='sunrise'>"sunrise"</span> (Heure du lever du soleil) </h2> <h2> <span id='sunset'>"sunset"</span> (Heure du coucher du soleil) </h2> <h2> <span id='timezone'>"timezone"</span> H GMT Time zone </h2> <script> let firstnumber, secondnumber; // 验证纬度输入 do { firstnumber = prompt("entrez la latitude (十进制,例如48.8566)"); } while (isNaN(Number(firstnumber)) || firstnumber === null); // 验证经度输入 do { secondnumber = prompt("entrez la longitude (十进制,例如2.3522)"); } while (isNaN(Number(secondnumber)) || secondnumber === null); async function main(){ try { const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${Number(firstnumber)}&lon=${Number(secondnumber)}&units=metric&lang=fr&appid=XXX`); if (!response.ok) { throw new Error(`API请求失败,状态码:${response.status}`); } const meteo = await response.json(); console.log(meteo); displayWeatherInfos(meteo); } catch (error) { console.error('获取天气数据出错:', error); alert('无法获取天气数据,请检查输入是否正确、API密钥是否有效或网络连接'); } } function displayWeatherInfos(data){ const temperature = data.main.temp; const pressure = data.main.pressure; const visibility = data.visibility; const windspeed = data.wind.speed; const winddire = data.wind.deg; const clouds = data.clouds.all; const sunrise = data.sys.sunrise; const sunset = data.sys.sunset; const timezone = data.timezone; document.querySelector('#temperature').textContent = Math.round(temperature); document.querySelector('#pressure').textContent = pressure; document.querySelector('#visibility').textContent = (visibility/1000); document.querySelector('#windspeed').textContent = Math.round(windspeed*3.6); document.querySelector('#winddire').textContent = winddire; document.querySelector('#clouds').textContent = clouds; document.querySelector('#sunrise').textContent = new Date(sunrise*1000).toLocaleTimeString('fr-FR'); document.querySelector('#sunset').textContent = new Date(sunset*1000).toLocaleTimeString('fr-FR'); document.querySelector('#timezone').textContent = timezone/3600; } main(); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Pierre
相关产品推荐
相关产品推荐

