2017-03-25 51 views
-2

我正在嘗試使用OpenWeatherMap並獲取JSON以獲取天氣。 在控制檯中我看到404的消息,但是當我手動訪問網址它給了我正確的JSON即使鏈接正常工作,也要獲取404 JSON

var latitude; 
 
var longitude; 
 
var apiId = "c440e3f473378f9705827ed71efe5dcc"; 
 
var request = new XMLHttpRequest(); 
 

 
function getLocation() { 
 

 
    if (navigator.geolocation) { 
 

 
    navigator.geolocation.getCurrentPosition(function getPosition(position) { 
 
     latitude = position.coords.latitude; 
 
     longitude = position.coords.longitude; 
 
     getJson(); 
 
    }); 
 

 
    } else { 
 
    alert('Geo location not working or not supported by your browser.'); 
 
    } 
 

 
} 
 

 
function getJson() { 
 

 
    request.open('GET', "api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=" + apiId + ""); 
 

 
    request.onload = function(data) { 
 
    console.log(data); 
 
    }; 
 

 
    request.send(); 
 

 
} 
 
getLocation();

+0

你錯過了你的網址中的協議。雖然我們人類瞭解這是一個uri,並且您的瀏覽器將嘗試糾正您的計算機不知道如何處理它。預先加上'http://'或'https://'或甚至可以'www'。 – Xorifelse

+0

我假設你在你的設備本地進行了測試(沒有任何本地服務器),這意味着你必須在每個鏈接開始時使用「https://」或「http://」,否則它只會假定它默認是'file:///'。 – Saharsh

+0

謝謝@Saharsh我使用codepen,所以我有問題,因爲OpenWeatherMap使用http,它不工作 –

回答

2

您需要在您的網址的開頭指定http

request.open('GET', "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=" + apiId + ""); 
+0

謝謝,但現在我得到錯誤,請求被阻止,因爲請求應該是「https」。我將它添加到URL並且鏈接不起作用(我正在使用代碼筆) –

+0

你是什麼意思?「它不起作用?」你有錯誤嗎? –

相關問題