我开始制作天气应用程序,但在链接 API 时不断收到“400 错误请求”错误。任何想法可能是什么?我也在它下面看到“获取失败加载:获取”。
HTML:
<div class = 'header'>
<h1> Weather Dashboard </h1>
<input type="text" class="city" placeholder="City Search">
<!-- Hidden Recent Searches Bar with Bootstrap -->
<ul class="list-group list-group-horizontal-sm">
</ul>
<div class="btnContainer">
<button class= "goBtn"> Go</button>
</div>
</div>
JS:
// Declaring Variables: -----------------------------------------------------------------//
var goBtn = document.querySelector('.goBtn');
var APIKey = "d04c941f9a17d4fd069f2142973171ec";
var city = document.querySelector('.city');
var searchedCities = [];
function getForecast() {
var queryUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city.value + "&appid=" + APIKey;
fetch(queryUrl)
.then(function (response) {
return response.json();
});
};
goBtn.addEventListener('click', getForecast());
答案 0 :(得分:1)
您实际上是在调用函数 getForecast()
,而不是在调用 addEventListener
时传递对它的引用。
因此你需要改变
goBtn.addEventListener('click', getForecast());
到
goBtn.addEventListener('click', getForecast);
'400 bad request' 是由于调用 openweathermap.com 的 api 而未将城市作为查询参数传递的结果。我想这会在您加载页面后意外发生。如果您通过例如检查响应,您也会注意到这一点浏览器开发者工具。