0
您好我正在使用JavaScript創建我的第一個Web應用程序並使用API從www.openweathermap.org/獲取數據我已經使用API密鑰正如文檔中提到的,它仍然給出了未授權的錯誤。調用某個函數時出現此錯誤是否有其他原因?先謝謝你。錯誤401:未經授權,甚至在使用API密鑰時收到,但使用www.openweathermap.org
var APPID = "my_secret_key";
var temp;
var loc;
var icon;
var wind;
var humidity;
var direction;
function updateByZip(zip){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"zip = " + zip +
"&APPID =" + APPID ;
sendRequest(url);
}
function sendRequest(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var data = JSON.parse(xmlhttp.responseText) ;
var weather = {};
weather.wind = data.wind.speed;
weather.direction = data.wind.deg;
weather.loc = data.name;
weather.temp = data.main.temp;
weather.icon = data.weather[0].id;
weather.humidity=data.main.humidity;
update(weather);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
將該URL放入瀏覽器中工作得很好。 「sendRequest」究竟做了什麼?也許它錯誤地發送POST? –
發送請求發送接收天氣數據的請求。如果你願意,我可以添加代碼。我也使用「GET」 –
我相信你有一個CROS問題。上次我試圖從OpenWeatherMap獲取數據時,它無法工作。 (我發現這[[小提琴](http://jsfiddle.net/rover/HWAFG/)和控制檯顯示[CORS錯誤](http://i.imgur.com/QXKayKz.png)。 – Tico