使用JavaScript调用OpenWeatherMap API获取天气数据遇问题及数据访问求助
天气API调用与数据访问问题
我正在用HTML、CSS、JavaScript开发一款天气应用,调用了OpenWeatherMap的实时天气API,但浏览器控制台未显示预期结果,也不知道如何访问返回数据中的weather.main、main.temp、main.humidity、wind.speed属性。
当前代码
async function getData(){ let response = await fetch(weatherAPI); let data = await response.json(); return data; } console.log(getData());
控制台当前输出
Promise {<pending>} [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: Object base: "stations" clouds: {all: 20} cod: 200 coord: {lon: -0.1257, lat: 51.5085} dt: 1684501221 id: 2643743 main: {temp: 15.6, feels_like: 14.86, temp_min: 14.72, temp_max: 17.25, pressure: 1026, …} name: "London" sys: {type: 2, id: 2075535, country: 'GB', sunrise: 1684469018, sunset: 1684525832} timezone: 3600 visibility: 10000 weather: [{…}] wind: {speed: 3.6, deg: 50} [[Prototype]]: Object
预期JSON结果
{ "coord": { "lon": 10.99, "lat": 44.34 }, "weather": [ { "id": 501, "main": "Rain", "description": "moderate rain", "icon": "10d" } ], "base": "stations", "main": { "temp": 298.48, "feels_like": 298.74, "temp_min": 297.56, "temp_max": 300.05, "pressure": 1015, "humidity": 64, "sea_level": 1015, "grnd_level": 933 }, "visibility": 10000, "wind": { "speed": 0.62, "deg": 349, "gust": 1.18 }, "rain": { "1h": 3.16 }, "clouds": { "all": 100 }, "dt": 1661870592, "sys": { "type": 2, "id": 2075663, "country": "IT", "sunrise": 1661834187, "sunset": 1661882248 }, "timezone": 7200, "id": 3163858, "name": "Zocca", "cod": 200 }
解决方案
1. 获取实际返回数据
async函数默认返回Promise对象,直接console.log(getData())只会打印Promise,而非API返回的JSON数据。你可以用以下两种方式获取数据:
方式一:使用await(需在async函数内执行)
async function getData(){ let response = await fetch(weatherAPI); let data = await response.json(); return data; } async function init() { const weatherData = await getData(); console.log(weatherData); // 打印预期的JSON数据 } init();
方式二:使用.then()链式调用
async function getData(){ let response = await fetch(weatherAPI); let data = await response.json(); return data; } getData().then(weatherData => { console.log(weatherData); // 打印预期的JSON数据 });
2. 访问目标属性
返回数据中weather是数组类型,其他属性为对象类型,访问方式如下:
- 天气状况(
weather.main):weatherData.weather[0].main - 气温(
main.temp):weatherData.main.temp - 湿度(
main.humidity):weatherData.main.humidity - 风速(
wind.speed):weatherData.wind.speed
示例:
getData().then(weatherData => { console.log("天气状况:", weatherData.weather[0].main); console.log("气温:", weatherData.main.temp); console.log("湿度:", weatherData.main.humidity); console.log("风速:", weatherData.wind.speed); });
内容的提问来源于stack exchange,提问作者joyalgeorgekj
相关产品推荐
相关产品推荐

