2016-06-08 8 views
11

Ich versuche eine Wetter-App zu erstellen, die das Wetter und die Temperatur von vielen Tagen der Woche anzeigt. Ich benutze derzeit openweathermap api für diese Aufgabe, die Sache ist, dass die Informationen, die ich will (das ist das Datum des Wetters) nur im XML-Format kommt. Da ich es in ES6 (ES2015) aus akademischen Gründen umbauen möchte, wollte ich auch die Fetch-API verwenden, aber da die Fetch-Methode es analysiert, liefert es nur einen Fehler. also wie kann ich es holen oder mby gibt es einen besseren Weg, es zu tun.So holen Sie XML mit 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)) 

Antwort

7

Ich denke, der Fehler aus dieser Funktion kommt: response => response.json() da die Antwort kein gültiges JSON-Objekt ist (es ist XML).

Soweit ich weiß, gibt es keinen nativen XML-Parser für fetch, aber Sie können die Antwort als Text und verwenden Sie ein Drittanbieter-Tool, um das eigentliche Parsen, zum Beispiel jQuery hat eine $.parseXML() Funktion.

Es wird in etwa so aussehen:

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

kann ich bestätigen, dass es keine native XML-Parser für holen. Siehe https://developer.mozilla.org/en-US/docs/Web/API/Response#Methods. – Marco

13

mit nativen DOMParser getCurrentCity (Standort) geschrieben werden kann:

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