如何解决是否可以从API获取值? HTML
我正在尝试制作一个小天气项目,并且正在使用此API来处理多伦多weather = https://weather.gc.ca/wxlink/wxlink.html?cityCode=on-143&lang = e 有谁知道我如何获取api中的值并将其放入标头中?
解决方法
根据documentation,似乎他们没有 proper API,但是您仍然有2个相对不错的选择:
- 将您链接到的页面嵌入到HTML中。可以这样完成:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div style="text-align: center;">
<h1>Weather App</h1>
<p style="font-size: 1.45rem">Check the wather forecast for today:</p>
<!-- Begin WeatherLink Fragment -->
<iframe title="Environment Canada Weather" width="287px" height="191px" src="https://weather.gc.ca/wxlink/wxlink.html?cityCode=on-143&lang=e" allowtransparency="true" frameborder="0"></iframe>
<!-- End WeatherLink Fragment -->
</div>
</body>
</html>
如果您需要对数据进行更细粒度的控制,则可以选择第二种选择。
- RSS供稿
此选项也很难。您无法从客户端发出请求,因为我们尝试读取的网站未设置所需的标头。这样,您将只能从服务器读取它。
您没有指定您的应用程序是否具有后端(如果有),但是要完成此特定任务,它就必须这样做。
这是一个提取所需数据的node.js代码段:
const https = require('https');
const xml2js = require('xml2js');
const parser = new xml2js.Parser();
const throwError = message => {
throw new Error(message);
};
/**
* Extracts YYYY-MM-DD from YYYY-MM-DDTHH:MM:SSZ
*
* @param {Date | string} date Date object or ISO string
*
* @returns {string} YYYY-MM-DD part of ISO date
*/
const getISODate = (date) => {
if (typeof date === 'string') {
return date.split('T')[0];
}
return date.toISOString().split('T')[0]
};
/**
* Gets XML atom feed from https://weather.gc.ca/,* parses it,and extracts the needed data.
*
* @see https://weather.gc.ca/business/index_e.html
* @see https://weather.gc.ca/rss/city/on-143_e.xml
*
* @returns {void} nothing
*/
const getTorontoWeather = () => {
// Make https request
https.get('https://weather.gc.ca/rss/city/on-143_e.xml',(res) => {
const { statusCode } = res;
if (statusCode !== 200) { // Ok range might be broader
throwError('Request failed');
}
res.setEncoding('utf8');
let rawXMLString = '';
// Add a chunk of data at a time to the total
res.on('data',chunk => rawXMLString += chunk);
res.on('end',() => { // Finished reading data
parser.parseString(rawXMLString,(err,res) => {
if (err) {
throwError('XML parsing failed');
}
// Object that represents entire feed
const feed = res.feed;
const today = getISODate(new Date());
// Find today entries
const todayEntries = feed.entry.filter((entry) => {
return (
getISODate(entry.updated[0]) === today &&
entry.category.find(category => category.$.term === 'Current Conditions')
);
})
console.log(todayEntries);
});
});
}).on('error',() => {
throwError('Request failed');
})
};
getTorontoWeather();
它使用xml2js library来解析XML。
现在,当在后端准备好数据时,您可以:
- 使用某些模板引擎渲染整个页面(需要相当复杂的设置)。
- 从客户端(更轻松)向您的入口点进行请求。
UPD : 或者,您可以使用cors-anywhere获取RSS feed,然后使用DOMParser对其进行解析。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。