【问题标题】:Display Data from fetch api显示来自 fetch api 的数据
【发布时间】:2021-10-24 23:22:50
【问题描述】:

您好,我想从 avascan api 获取数据并将其显示为 html,但我无法做到这一点。我尝试过获取 api、json 和 ajax 方式,但没有一个对我有用。有什么建议?这是我的 html https://avascan.info/api/v1/home/statistics

const api_url = 'https://avascan.info/api/v1/home/statistics';


async function getAVA() {
  const response = await fetch(api_url);
  const data = await response.json();
  const {
    blockchains,
    validators
  } = data;
  document.getElementById('lat').textContent = blockchains.toFixed(2);
  document.getElementById('lon').textContent = validators.toFixed(2);
}

getAVA();

setInterval(getAVA, 1000);
<h1>What the stats?</h1>

<p>
  blockchains: <span id="lat"></span>°<br /> validators: <span id="lon"></span>°
</p>

<div id="issMap"></div>

【问题讨论】:

标签: javascript jquery json jsonp fetch-api


【解决方案1】:

如前所述,您遇到了 CORS 保护错误。

不过,您似乎需要使用 GraphQL API:https://graphql.avascan.info/

看看这个简单的例子:

      async function getAVA() {

        fetch('https://graphql.avascan.info', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
            query: `
            query {
                stats {
                    priceAvaxUsd,
                    connectedNodes
                }
            }`
            }),
            })
            .then((res) => res.json())
            .then((result) => console.log(result));
      }

      getAVA();

【讨论】:

  • 我也需要总数。验证器和区块链在 html 中显示它们,似乎无法检索它们,顺便说一句,我如何显示这个控制台。用html记录数据?
  • 看来你需要等待才能完成你所需要的。 GraphQL API 已弃用,新的​​ API 尚不可用。 docs.avascan.info/quickstart-graphql#api-version-0-3
  • 要在 html 而不是 console.log 中显示数据,您需要将这些命令 document.getElementById('lat').textContent = result.data.stats.connectedNodes.toFixed(2); 移动到最后一个 then
【解决方案2】:

您似乎遇到此错误:请求的资源上没有“Access-Control-Allow-Origin”标头。

这是一种 CORS 保护,您可能需要某些要求才能获取此数据,例如 api 密钥,或更新您在 fetch 方法中的选项的配置

这里有一个resource 来帮忙

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    相关资源
    最近更新 更多