2016-06-10 25 views
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(); 
     } 
+0

將該URL放入瀏覽器中工作得很好。 「sendRequest」究竟做了什麼?也許它錯誤地發送POST? –

+0

發送請求發送接收天氣數據的請求。如果你願意,我可以添加代碼。我也使用「GET」 –

+0

我相信你有一個CROS問題。上次我試圖從OpenWeatherMap獲取數據時,它無法工作。 (我發現這[[小提琴](http://jsfiddle.net/rover/HWAFG/)和控制檯顯示[CORS錯誤](http://i.imgur.com/QXKayKz.png)。 – Tico

回答

1

這是您的URL中等號附近的空格。這可能是urlencoding的空間,併發送您的參數爲APPID%20這是不被認爲是有效的。

var url = "http://api.openweathermap.org/data/2.5/weather?" + 
      "zip=" + zip + 
      "&APPID=" + APPID; 
+0

是啊這工作很好!!謝謝!!雖然我的功能還有一些錯誤,請檢查一下。 –

相關問題