我试图通过在客户端使用JavaScript脚本从API检索天气数据。代码是这样的:
<script>
async function fetchWeatherData(){
var url = "http://www.7timer.info/bin/api.pl?lon=-3.57&lat=40.49&product=astro&output=json";
var weather_data = await fetch(url);
var weather_json = await weather_data.json();
return weather_json.dataseries[0].temp2m;
}
document.write(await fetchWeatherData());
</script>
不幸的是,这段代码没有像我预期的那样工作。一个非常相似的Node.JS/Express在服务器端工作得很好:
export async function getTemperature(iata){
let latLong = latLongAirports.find(el => el.iata === iata);
var url = "http://www.7timer.info/bin/api.pl?lon=" + latLong.long + "&lat=" + latLong.lat + "&product=astro&output=json"
const response = await fetch(url);
const jsonTemperature = await response.json();
return jsonTemperature.dataseries[0].temp2m;
}
我在客户端/服务器端代码之间缺少或不理解什么?
不能使用"top level async"在普通脚本标签中。您需要将脚本标记声明为type="module"
。然后它会像你期望的那样工作。
<script type="module">
async function fetchWeatherData(){
var url = "http://www.7timer.info/bin/api.pl?lon=-3.57&lat=40.49&product=astro&output=json";
var weather_data = await fetch(url);
var weather_json = await weather_data.json();
return weather_json.dataseries[0].temp2m;
}
document.write(await fetchWeatherData());
</script>