首页 > 解决方案 > 是否可以从 API 获取值?(HTML)

问题描述

我正在尝试制作一个小天气项目,并且我正在将此 API 用于多伦多天气 = https://weather.gc.ca/wxlink/wxlink.html?cityCode=on-143 &lang=e 有人知道我是怎么做到的吗可以获取 api 中的值并将其放入标头中吗?

标签: htmlapinumbersweather

解决方案


根据文档,他们似乎没有合适的API,但您仍然有 2 个相对不错的选择:

  1. 将您链接到的页面嵌入到您的 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&amp;lang=e" allowtransparency="true" frameborder="0"></iframe>
        <!-- End WeatherLink Fragment -->
    </div>
</body>
</html>

如果您需要对数据进行更细粒度的控制,您有第二种选择。

  1. 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。

现在,当您在后端准备好数据时,您可以:

  1. 使用一些模板引擎渲染整个页面(需要相当复杂的设置)。
  2. 从客户端向您的入口点发出请求(更容易)。

UPD :或者您可以使用cors-anywhere获取 RSS 提要并使用DOMParser对其进行解析。


推荐阅读