【发布时间】:2020-08-21 21:21:21
【问题描述】:
当我把它放到浏览器中时,它会带回带有所有天气数据的 json 对象: http://api.openweathermap.org/data/2.5/weather?zip=90210&units=imperial&appid={API 密钥}
但是,我在 htdocs 文件夹中使用我的 XAMPP Apache 来尝试在我的代码中对其进行测试。有人可以看看我的代码,看看这里有什么问题吗?非常感谢您的帮助。
var weatherInfo = document.getElementById("weather");
var zipCodeForm = document.getElementById("zipCodeForm");
function getWeather(zipCode){
//create the url for the request
var endpoint = "http://api.openweathermap.org/data/2.5/weather";
var apiKey = {API Key};
var queryString = "zip=" + zipCode + "&units=imperial&appid=" + apiKey;
var url = endpoint + "?" +queryString;
//create the request to get the weather data
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", responseReceivedHandler);
xhr.requestType = "json";
xhr.open("GET", url);
xhr.send();
console.log("getWeather")
console.log(xhr.response.status);
}
function responseReceivedHandler(){
if(this.status === 200){
weatherInfo.innerHTML = "Current temperature: " + this.response.main.temp;
}
else{
weatherInfo.innerHTML="Not working";
}
console.log("responseReceivedHandler")
}
getWeather(90210);
<body>
<form id="zipCodeForm">
<label for="zipCode">Please enter your zip code: </label>
<input type="text" name="zipCode" id="zipCode">
<input type="submit" name="submit">
</form>
<div id="weather"></div>
</body>
【问题讨论】:
-
如果没有您的 API 密钥,我们将很难对其进行测试。 (请不要分享您的 API 密钥!)另外,“它不起作用”有点含糊。您是否在浏览器的控制台中看到任何错误?
-
{"coord":{"lon":-118.41,"lat":34.09},"weather":[{"id":800,"main":"Clear","description ":"晴空","icon":"01d"}],"base":"stations","main":{"temp":81.19,"feels_like":80.19,"temp_min":75.2,"temp_max ":86,"压力":1013,"湿度":44},"能见度":16093,"风":{"速度":5.82,"度":220},"云":{"全部": 1},"dt":1588786879,"sys":{"type":1,"id":5872,"country":"US","sunrise":1588769932,"sunset":1588819291},"timezone" :-25200,"id":0,"name":"Beverly Hills","cod":200}......................浏览器链接给了我所有正确的数据。但是当我通过运行代码对其进行测试时,出现 401 错误
-
当我删除“?”在我的 url 变量中,我收到 401 错误。当我重新添加它时,我变得不确定。我感觉像“?”不过应该在那里
-
什么是“浏览器链接”?您在哪里看到/检测到这个 401 错误? 401 是 unauthorized 的 HTTP 代码,这意味着您可能没有指定正确的 API 密钥。
-
“?”是 URL 的一部分。为什么要删除它?
标签: javascript apache api xampp openweathermap