【问题标题】:How to use cryptocomapre api to display price of BTC?如何使用 cryptocomapre api 显示 BTC 的价格?
【发布时间】:2019-01-01 11:42:42
【问题描述】:

我正在开发一个电子应用程序,我正在使用 cryptocompare api 来显示 BTC 价格,但它不显示。我已经尝试了所有我能想到的解决方案,我们将不胜感激!

const electron = require('electron');
const path = require('path');
const BrowserWindow = electron.remote.BrowserWindow;
const axios = require('axios');

const notifyBtn = document.querySelector('.notify-btn');
const price = document.querySelector('.price');
const targetPrice = document.querySelector('.target-price');

function  getBTC(){
    const cryptos = axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD&api_key={api_key}')
        price.innerHTML = '$'+cryptos
    }

getBTC();
setInterval(getBTC, 20000);

它给了我一个'$[object Promise]'的输出

【问题讨论】:

    标签: api electron bitcoin


    【解决方案1】:

    在 axios 的文档中,它说你需要这样做:

    axios.get(url)
        .then(function (response) {
            // do something with response
        });
    

    这是因为axios.get 返回的值不是响应,而是将解析为响应的承诺。 (所以它被强制转换为字符串[object Promise]。)如果您不知道这意味着什么,请阅读this link。基本上,promise 是一种处理需要很长时间才能运行的任务(例如 api 调用)的方法,而不会阻止其他 JavaScript 代码运行。但无论如何,你想要的是这样的:

    function  getBTC(){
        axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD&api_key={api_key}')
            .then(function(response) {
                var data = response.data;
                var cryptos = // get cryptos from data somehow
                price.innerHTML = '$'+cryptos;
            });
    }
    

    我还没有详细阅读 axios 文档。我相信你正在寻找的是response.data,但我不能告诉你更多。尝试console.log('Response:', response); 了解响应的结构。

    【讨论】:

    • 现在我得到 $undefined.
    • 这不是一个完整的答案,因为我无法从文档中找出所有细节。我的意思是您需要通过记录它来了解response 的结构(或者可能通过比我更彻底地阅读文档)。然后你可以用更明智的东西替换var cryptos 行。目前它正在将该行加入下一行,因为它不以分号结尾;所以它相当于var cryptos; price.innerHTML = '$'+cryptos; cryptos = price.innerHTML;。这就是为什么它将价格设置为$undefined
    猜你喜欢
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 2014-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多