2016-06-08 104 views
11

我正試圖製作一個天氣應用程序,顯示一週中多天的天氣和溫度。我目前正在使用openweathermap api來執行此類任務,事情是我想要的信息(即天氣的日期)只能以xml格式顯示。 由於我在ES6(ES2015)中重建它,出於學術原因,我也想使用fetch api,但是由於fetch方法解析它,它只是提供了一個錯誤。 所以我如何獲取它或mby有一個更好的方法來做到這一點。如何使用抓取API獲取XML

let apis = { 
    currentWeather: { //get user selected recomendation weather 
     api:"http://api.openweathermap.org/data/2.5/forecast/daily?lat=", 
     parameters: "&mode=xml&units=metric&cnt=6&APPID=/*api key*/", 
     url: (lat, lon) => { 
      return apis.currentWeather.api + lat + "&lon=" + lon + 
        apis.currentWeather.parameters 
     } 
    } 
}; 
function getCurrentLoc() { 
    return new Promise((resolve, reject) => navigator.geolocation 
              .getCurrentPosition(resolve, reject)) 
} 
function getCurrentCity(location) { 
    const lat = location.coords.latitude; 
    const lon = location.coords.longitude; 
    return fetch(apis.currentWeather.url(lat, lon)) 
    .then(response => response.json()) 
    .then(data => console.log(data)) 
} 
getCurrentLoc() 
.then(coords => getCurrentCity(coords)) 

回答

7

我猜的錯誤是由該功能來:response => response.json()由於響應不是有效的JSON對象(它的XML)。

據我所知,fetch沒有原生的XML解析器,但您可以將響應作爲文本處理,並使用第三方工具進行實際的解析,例如jQuery具有$.parseXML()函數。

它看起來是這樣的:

function getCurrentCity(location) { 
    const lat = location.coords.latitude; 
    const lon = location.coords.longitude; 
    return fetch(apis.currentWeather.url(lat, lon)) 
     .then(response => response.text()) 
     .then(xmlString => $.parseXML(xmlString)) 
     .then(data => console.log(data)) 
} 
+3

我可以證實,有因爲沒有原生XML解析器取。請參閱https://developer.mozilla.org/en-US/docs/Web/API/Response#Methods。 – Marco

13

使用本機的DOMParser getCurrentCity(位置)可以寫成:

function getCurrentCity(location) { 
 
    const lat = location.coords.latitude; 
 
    const lon = location.coords.longitude; 
 
    return fetch(apis.currentWeather.url(lat, lon)) 
 
     .then(response => response.text()) 
 
     .then(str => (new window.DOMParser()).parseFromString(str, "text/xml")) 
 
     .then(data => console.log(data)) 
 
}