如何从 api 获取数据?

How to fetch data from api?

我想从 api 获取数据(尤其是市值)并将其显示在我的 div 中。但是我的 html 显示没有执行数据。我可能做错了什么?

<text id="result"></text>

  <script>
  // API for get requests 

  let fetchRes = fetch(
        "https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX"); 

   // fetchRes is the promise to resolve 

   // it by using.then() method 

   fetchRes.then((res) => res.json())
    .then((result) => {
      console.log(result);
      document.getElementById('result').innerHTML = result.config.data.0.market_cap;
    })
    .catch(error => {
      console.log(error);
    })
      
    </script>

两条建议:

  1. 为什么不直接将 .then() 链接到 fetch()
  2. 您似乎对如何访问结构中的数据有些困惑 - 您所追求的是 result.data[0].market_cap

// API for get requests 

let fetchRes = fetch("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
  .then((res) => res.json())
  .then((result) => {
    console.log(result);
    document.getElementById('result').innerHTML = result.data[0].market_cap;
  })
  .catch(error => {
    console.log(error);
  })
<text id="result"></text>

旁白:您可能应该使包含在此处的 API 密钥无效,因为它现在已在 public 中,并且可用于伪造请求,因为您对此 API.

我正在使用 jQuery 框架 轻松完成此操作。 检查下面的代码。

<script>
    $.get(
        "https://api.lunarcrush.com/v2",
        {
            data: "assets",
            key: "n8dyddsipg5611qg6bst9",
            symbol: "AVAX"
        },
        function (result){
            data = JSON.parse(result);
        }
    );
</script>

您可以通过在 <head> 标签中添加以下代码来使用 jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

使用result.config.data[0].market_cap;而不是 result.config.data.0.market_cap;

let fetchRes = fetch( 
"https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX"); 

  

        // fetchRes is the promise to resolve

        // it by using.then() method

        fetchRes.then((res) => res.json())
    .then((result) => {
        console.log(result);
        document.getElementById('result').innerHTML = result.config.data[0].market_cap;
    })
    .catch(error => {
        console.log(error);
    });

你可以让它更简洁:

const fetchData = async(url) => (await fetch(url)).json();

fetchData("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
  .then(res => {
    result.innerText = res.data[0].market_cap;
  })
  .catch(err => {
    console.log(err);
  });
<text id="result"></text>