Search code examples
javascriptjqueryjsonjsonpfetch-api

Display Data from fetch api


Hi i want to fetch data from avascan api and display it in html, but i am not able to do this. I have tried fetch api, json and ajax ways but none worked for me. Any suggestions? This is my 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>


Solution

  • You are getting a CORS protection error, as mentioned before.

    However it seems you need to use a GraphQL API: https://graphql.avascan.info/

    Look at this quick example:

          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();