从GitHub Pages托管时从OpenWeatherMap获取数据时出现错误。

huangapple go评论73阅读模式
英文:

Error when fetching data from OpenWeatherMap while hosting on Github Pages

问题

我是编程方面的新手,我想编写一个天气网站。因此,我正在使用OpenWeatherMap API。

每次我想从这个API获取数据时,我都会收到以下错误消息:<https://i.stack.imgur.com/ZcBFx.png>

看起来我的代码与GitHub页面的代码冲突,因为当我检查错误发生的确切位置时,我注意到它部分地不在我的代码中:

我的代码:

// 使用给定的URL获取天气数据
function fetchWeather() {
    if (positionError(lat, lon)) {
        let weatherURL = "https://api.openweathermap.org/data/2.5/forecast?lat=" + lat + "&lon=" + lon + "&appid=" + apiKey + "&units=metric&lang=en";

        try {
            fetch(weatherURL)
                .then(response => response.json())
                .then(data => {
                    if (data["city"] !== undefined) {
                        console.log(weatherURL);
                    } else {
                        alert("无法获取给定纬度和经度值的数据!");
                    }
                });
        } catch (e) {
            console.error("无法获取天气的URL!");
        }
    }
}

GitHub页面的代码:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'">
    <title>Site not found &middot; GitHub Pages</title>
    <!-- 其他样式和元素 -->
  </head>
  <body>
    <!-- 页面内容 -->
  </body>
</html>

我将我的代码和网页链接在这里:GitHub上的代码 - 网站

要重现错误,您必须首先获取您的位置,因为没有位置,您无法获取天气数据。点击“获取位置”按钮后,您必须点击“检查天气”。错误就会在那时发生。

我已经检查了.JSON文件是否有错误字符或是否有任何未按预期工作的问题。

它在我的本地服务器上完全正常工作,所以这肯定是GitHub页面的问题,但我真的找不出问题所在。

英文:

I am pretty new to coding and I wanted to code a weather website. So I am using the OpenWeatherMap API.

Everytime I wanna fetch the data from this API, I am getting the following error: <https://i.stack.imgur.com/ZcBFx.png>

It seems like my code is conflicting with the code of github pages, because when I check where exactly the error is occurring, I noticed it is partially not in my code:

My Code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 // Fetches the weather data with the given url
    function fetchWeather() {
        if (positionError(lat, lon)) {
            let weatherURL = &quot;https:/api.openweathermap.org/data/2.5/forecast?lat=&quot; + lat + &quot;&amp;lon=&quot; + lon + &quot;&amp;appid=&quot; + apiKey + &quot;&amp;units=metric&amp;lang=en&quot;;

            try {
                fetch(weatherURL)
                    .then(response =&gt; response.json())
                    .then(data =&gt; {
                        if (data[&quot;city&quot;] !== undefined) {
                            console.log(weatherURL);
                        } else {
                            alert(&quot;Cannot fetch data for the given lat and lon values!&quot;);
                        }
                    });
            } catch (e) {
                console.error(&quot;Can&#39;t fetch url for weather!&quot;);
            }
        }
    }

<!-- end snippet -->

Github pages Code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv=&quot;Content-type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;
    &lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src &#39;none&#39;; style-src &#39;unsafe-inline&#39;; img-src data:; connect-src &#39;self&#39;&quot;&gt;
    &lt;title&gt;Site not found &amp;middot; GitHub Pages&lt;/title&gt;
    &lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
      body {
        background-color: #f1f1f1;
        margin: 0;
        font-family: &quot;Helvetica Neue&quot;, Helvetica, Arial, sans-serif;
      }

      .container { margin: 50px auto 40px auto; width: 600px; text-align: center; }

      a { color: #4183c4; text-decoration: none; }
      a:hover { text-decoration: underline; }

      h1 { width: 800px; position:relative; left: -100px; letter-spacing: -1px; line-height: 60px; font-size: 60px; font-weight: 100; margin: 0px 0 50px 0; text-shadow: 0 1px 0 #fff; }
      p { color: rgba(0, 0, 0, 0.5); margin: 20px 0; line-height: 1.6; }

      ul { list-style: none; margin: 25px 0; padding: 0; }
      li { display: table-cell; font-weight: bold; width: 1%; }

      .logo { display: inline-block; margin-top: 35px; }
      .logo-img-2x { display: none; }
      @media
      only screen and (-webkit-min-device-pixel-ratio: 2),
      only screen and (   min--moz-device-pixel-ratio: 2),
      only screen and (     -o-min-device-pixel-ratio: 2/1),
      only screen and (        min-device-pixel-ratio: 2),
      only screen and (                min-resolution: 192dpi),
      only screen and (                min-resolution: 2dppx) {
        .logo-img-1x { display: none; }
        .logo-img-2x { display: inline-block; }
      }

      #suggestions {
        margin-top: 35px;
        color: #ccc;
      }
      #suggestions a {
        color: #666666;
        font-weight: 200;
        font-size: 14px;
        margin: 0 10px;
      }

    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;

    &lt;div class=&quot;container&quot;&gt;

      &lt;h1&gt;404&lt;/h1&gt;
      &lt;p&gt;&lt;strong&gt;There isn&#39;t a GitHub Pages site here.&lt;/strong&gt;&lt;/p&gt;

      &lt;p&gt;
        If you&#39;re trying to publish one,
        &lt;a href=&quot;https://help.github.com/pages/&quot;&gt;read the full documentation&lt;/a&gt;
        to learn how to set up &lt;strong&gt;GitHub Pages&lt;/strong&gt;
        for your repository, organization, or user account.
      &lt;/p&gt;

      &lt;div id=&quot;suggestions&quot;&gt;
        &lt;a href=&quot;https://githubstatus.com&quot;&gt;GitHub Status&lt;/a&gt; &amp;mdash;
        &lt;a href=&quot;https://twitter.com/githubstatus&quot;&gt;@githubstatus&lt;/a&gt;
      &lt;/div&gt;

      &lt;a href=&quot;/&quot; class=&quot;logo logo-img-1x&quot;&gt;
        &lt;img width=&quot;32&quot; height=&quot;32&quot; title=&quot;&quot; alt=&quot;&quot; src=&quot;&quot;&gt;
      &lt;/a&gt;

      &lt;a href=&quot;/&quot; class=&quot;logo logo-img-2x&quot;&gt;
        &lt;img width=&quot;32&quot; height=&quot;32&quot; title=&quot;&quot; alt=&quot;&quot; src=&quot;&quot;&gt;
      &lt;/a&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

I am gonna link my code and the webpage here: Code from Github - The Website

To recreate the error, you have to get your Position first, because you cannot fetch the weatherdata without a location. After you clicked the "get position"-Button, you have to "check weather". The error happens right then.

I already checked the .JSON file for any wrong characters or if anything is not working like it should be.

It is completely working on my local server, so it has to be a problem with github pages, but I really can't figure out what it is.

答案1

得分: 0

在访问网站并检查天气后,我注意到错误信息中可能有一些有用的信息:

GET https://dafinndus.github.io/api.openweathermap.org/data/2.5/forecast?lat=45.5202471&amp;lon=-122.674194&amp;appid=6b73bc848d05bdb699cf0cfb49adf6f6&amp;units=metric&amp;lang=en 404

当展开错误以查看完整的URL时,似乎您的网站地址被添加到字符串中。然后仔细查看代码后,我认为问题可能很简单,只是在URL中缺少了一个斜杠:应该是https://api.openweather...。希望问题能如此明了!

我猜测,当请求看到单斜杠时,它会假定您想查看当前域的子目录。

英文:

After visiting the site and checking the weather, I noticed something in the error that might help:

GET https://dafinndus.github.io/api.openweathermap.org/data/2.5/forecast?lat=45.5202471&amp;lon=-122.674194&amp;appid=6b73bc848d05bdb699cf0cfb49adf6f6&amp;units=metric&amp;lang=en 404

When expanding the error to see the full URL, it looks like your own site's address is being added to the string. Then looking closer at the code, I think it could be as simple as missing a / in the URL: it should be https://api.openweather...... I hope it's that straightforward!

My guess is that when the request sees the single slash it's assuming you want to look at a subdirectory of the current domain.

答案2

得分: -1

这个错误是在尝试将HTML解析为JSON时生成的。

使用的URL存在问题。

另外,在https后只有一个/。

英文:

This error is generated when trying to parse HTML to JSON.

There is an issue with the used URL.

Also, you have only one / after https.

huangapple
  • 本文由 发表于 2023年8月4日 07:06:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76832077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定