如何使用fetch api获取XML [英] How to fetch XML with fetch api

查看:307
本文介绍了如何使用fetch api获取XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个天气应用程序,显示一周中许多天的天气和温度。我目前正在使用openweathermap api进行此类任务,事情是我想要的信息(即天气的日期)仅以xml格式提供。
因为出于学术原因我在ES6(ES2015)中重建它,我想也使用fetch api,但由于fetch方法解析它,它只是传递错误。
所以如何获取它或者mby有更好的方法。

I'm trying to making a weather app that displays the weather and the temperature of many days of the week. I'm currently using openweathermap api for such task, the thing is that the information that I want (that is the date of the weather) only comes in xml format. Since I'm rebuilding it in ES6(ES2015) for academic reasons I wanted to also use the fetch api but since the fetch method parses it, it just delivers an error. so how can i fetch it or mby there is a better way to do it.

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


推荐答案

使用原生DOMParser getCurrentCity(位置)可以写成:

Using native DOMParser getCurrentCity(location) can be written:

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

这篇关于如何使用fetch api获取XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆