我正在与 OpenWeatherMap 合作,以获取赫尔辛基等地的当前天气。
我最新的 MNWE(N 为
non
)是:
import axios from 'axios'
const apiKey = import.meta.env.VITE_OWM_API_KEY
const getCityCoordinatesApiUrl = (city) => {
return `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
}
const getCityWeatherApiUrl = (longitude, latitude) => {
return `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&appid=${apiKey}`
}
const getCityWeather = (city, weatherJsonContainer) => {
const url = getCityCoordinatesApiUrl(city)
let longitude = null
let latitude = null
axios.get(url).then(response => {
console.log("Hell", response.data)
longitude = response.data.coord.lon
latitude = response.data.coord.lat
})
.catch(error => {
console.log("Error in getCityWeather:", error)
alert(`Could not obtain weather of ${city}!`)
})
console.log("getCityWeather: received:", latitude, longitude)
const url2 = getCityWeatherApiUrl(longitude, latitude)
const outData = axios.get(url2).then(response => response.data)
console.log("getCityWeather: outData:", outData)
}
我的问题是
longitude
和latitude
保持为null
。我该如何解决这个问题?我已经为此工作了几个小时了。
您需要等待第一个请求完成。将代码放在 .catch() 后面的 .then() 语句中