Tri*_*ip1 29 javascript xml fetch-api
我正在尝试制作一个天气应用程序,显示一周中许多天的天气和温度.我目前正在使用openweathermap api进行此类任务,事情是我想要的信息(即天气的日期)仅以xml格式提供.由于我出于学术原因在ES6(ES2015)中重建它,我想也使用fetch api,但由于fetch方法解析它,它只是传递错误.所以我怎样才能获取它或者mby有更好的方法来实现它.
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))
Run Code Online (Sandbox Code Playgroud)
Juk*_*kaP 55
使用本机DOMParser getCurrentCity(location)可以编写:
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))
}Run Code Online (Sandbox Code Playgroud)
Gil*_*tzi 10
我猜错误来自这个函数:response => response.json()因为响应不是有效的JSON对象(它是XML).
据我所知,没有原生XML解析器fetch,但您可以将响应作为文本处理并使用第三方工具进行实际解析,例如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))
}
Run Code Online (Sandbox Code Playgroud)
可以使用 npm xml-js 库和 node-fetch 在 Node.js 中执行此操作,对于那些想要在 Node REPL 中进行测试的人。
首先,我们安装两个模块 xml-js 和 node-fetch :
npm install xml-js --save npm install node-fetch --save
将这两个包存储到 package.json 中。现在转到我们手头的问题 - 如何处理从 API 返回的 XML 数据。
考虑以下获取挪威特定气象站的示例:
const fetch = require('node-fetch');
const convert = require('xml-js');
let dataAsJson = {};
fetch('http://eklima.met.no/metdata/MetDataService?invoke=getStationsProperties&stations=68050&username=')
.then(response => response.text())
.then(str => {
dataAsJson = JSON.parse(convert.xml2json(str))
})
.then(() => {
console.log('Station id returned from the WS is:' +
`${dataAsJson.elements[0].elements[0].elements[0].elements[0].elements[0].elements
.filter(obj => { return obj.name == 'stnr'; })[0].elements[0].text} Expecting 68050 here!`
);
});
Run Code Online (Sandbox Code Playgroud)
我们现在得到了一个变量,该变量实际上使用 convert 的 xml2json 方法和 JSON.parse 从 XML 数据解析为 JSON 对象。如果我们想打印出对象,我们可以使用 JSON.stringify 将 JSON 对象转换为字符串。在这段代码中检索站 id 只是表明需要深入扫描给定键的对象图,因为将 XML 转换为 Json 通常会提供更深的对象图,因为包装的 XML 元素始终位于“ XML 对象 JSON 图形”。有一些关于深度搜索对象图的技巧可以深入寻找一个关键,比如GitHub 上的 obj-traverse 库