html - 是否可以从 API 获取值?(HTML)
问题描述
我正在尝试制作一个小天气项目,并且我正在将此 API 用于多伦多天气 = https://weather.gc.ca/wxlink/wxlink.html?cityCode=on-143 &lang=e 有人知道我是怎么做到的吗可以获取 api 中的值并将其放入标头中吗?
解决方案
根据文档,他们似乎没有合适的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 库来解析 XML。
现在,当您在后端准备好数据时,您可以:
- 使用一些模板引擎渲染整个页面(需要相当复杂的设置)。
- 从客户端向您的入口点发出请求(更容易)。
UPD :或者您可以使用cors-anywhere获取 RSS 提要并使用DOMParser对其进行解析。
推荐阅读
- angular - Safari 上的 Bitmovin 播放器不会从媒体 SourceConfig 加载字幕选择选项
- bash - 基本问题:在 Linux 中使用变量内容作为目录名
- c++ - C++ OpenGL,绘制形状返回错误
- javascript - 为什么 setState 不设置将我的数组附加到状态中?
- reactjs - nextProps.history.push 不会在登录时重新渲染组件
- c - 不带 printf 的指针地址 C
- android - 非常慢 - 从片段中更新数据绑定 UI
- c# - 解析不同格式的命令行参数
- http - Nginx 将所有流量重定向到 HTTPS 和非 www
- swift - Swift Digest 身份验证 async-http-client