当我尝试 link API 时收到“400 错误请求”
Getting a '400 Bad Request' when I try to link API
我开始制作天气应用程序,当我 link 我的 API 时,我不断收到“400 错误请求”错误。任何想法可能是什么?我也得到 'Fetch failed loading: GET' 就在它下面。
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());
您实际上是在调用函数 getForecast()
,而不是在对 addEventListener
的调用中传递对它的引用。
因此您需要更改
goBtn.addEventListener('click', getForecast());
至
goBtn.addEventListener('click', getForecast);
“400 错误请求”是调用 openweathermap.com 的 api 而未将城市作为查询参数传递的结果。我想这是在您加载页面后意外发生的。如果您通过例如检查响应,您也会注意到这一点浏览器开发者工具。
我开始制作天气应用程序,当我 link 我的 API 时,我不断收到“400 错误请求”错误。任何想法可能是什么?我也得到 'Fetch failed loading: GET' 就在它下面。
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());
您实际上是在调用函数 getForecast()
,而不是在对 addEventListener
的调用中传递对它的引用。
因此您需要更改
goBtn.addEventListener('click', getForecast());
至
goBtn.addEventListener('click', getForecast);
“400 错误请求”是调用 openweathermap.com 的 api 而未将城市作为查询参数传递的结果。我想这是在您加载页面后意外发生的。如果您通过例如检查响应,您也会注意到这一点浏览器开发者工具。