在使用JavaScript请求天气接口时,通常会涉及到以下几个基础概念和技术点:
以下是一个使用JavaScript请求天气接口的示例代码,使用的是OpenWeatherMap的免费API:
// 获取天气数据的函数
async function getWeather(city) {
const apiKey = 'YOUR_API_KEY'; // 替换为你的API密钥
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.error('Error fetching weather data:', error);
}
}
// 调用函数获取天气数据
getWeather('Beijing');
通过以上示例代码和常见问题解决方法,你可以更好地理解和使用JavaScript请求天气接口。
领取专属 10元无门槛券
手把手带您无忧上云