2016-06-08 13 views
11

Sto provando a creare un'app meteo che mostri il tempo e la temperatura di molti giorni della settimana. Attualmente sto usando openweathermap api per tale compito, il fatto è che l'informazione che voglio (cioè la data del tempo) arriva solo in formato xml. Dal momento che lo sto ricostruendo in ES6 (ES2015) per ragioni accademiche, volevo usare anche l'API di recupero ma, poiché il metodo di recupero lo analizza, fornisce solo un errore. così come posso recuperarlo o mby c'è un modo migliore per farlo.Come recuperare XML con fetch api

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)) 

risposta

7

Credo che l'errore viene da questa funzione: response => response.json() dal momento che la risposta non è un oggetto JSON valida (è XML).

Per quanto ne so, non c'è parser XML nativo per fetch, ma si può gestire la risposta come testo e utilizzare uno strumento di terze parti per fare il parsing vero e proprio, ad esempio jQuery ha una funzione $.parseXML().

Si avrà un aspetto simile:

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

Posso confermare che non c'è parser XML nativo per recupero. Vedi https://developer.mozilla.org/en-US/docs/Web/API/Response#Methods. – Marco

13

Utilizzando nativo DOMParser getCurrentCity (posizione) può essere scritta:

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)) 
 
}

Problemi correlati