# 注册并获取 API Key
访问 https://openweathermap.org/api 注册账号。记得在邮箱验证,生成一个新的 API 密钥
# 通过 axios, async/await 获取天气信息
替换 YOUR_API_KEY
为 API 密钥
在 fetchWeather
函数中,我们使用 axios.get()
方法发送一个 HTTP GET 请求到 OpenWeatherMap API,并传递了 API 密钥和查询参数。
天气数据被存储在 weather
状态变量中。capital
是城市名
const fetchWeather = async (capital) => { | |
try { | |
const response = await axios.get( | |
`https://api.openweathermap.org/data/2.5/weather?q=${capital}&appid=YOUR_API_KEY&units=metric` | |
); | |
setWeather(response.data); | |
} catch (error) { | |
console.error("Error fetching weather data:", error); | |
} | |
}; |
可以发现访问网址后得到 JSON 文件
{ | |
"coord": { | |
"lon": 116.3972, | |
"lat": 39.9075 | |
}, | |
"weather": [ | |
{ | |
"id": 800, | |
"main": "Clear", | |
"description": "clear sky", | |
"icon": "01d" | |
} | |
], | |
"base": "stations", | |
"main": { | |
"temp": 13.94, | |
"feels_like": 12.41, | |
"temp_min": 13.94, | |
"temp_max": 13.94, | |
"pressure": 1016, | |
"humidity": 39, | |
"sea_level": 1016, | |
"grnd_level": 1012 | |
}, | |
"visibility": 10000, | |
"wind": { | |
"speed": 1.78, | |
"deg": 233, | |
"gust": 3.11 | |
}, | |
"clouds": { | |
"all": 1 | |
}, | |
"dt": 1741584027, | |
"sys": { | |
"type": 1, | |
"id": 9609, | |
"country": "CN", | |
"sunrise": 1741559669, | |
"sunset": 1741601716 | |
}, | |
"timezone": 28800, | |
"id": 1816670, | |
"name": "Beijing", | |
"cod": 200 | |
} |