lemooljiang avatar

在前端中查询币价 / 网络研习社#74

lemooljiang

Published: 01 Nov 2020 › Updated: 01 Nov 2020在前端中查询币价 / 网络研习社#74

在前端中查询币价 / 网络研习社#74

coinmarketcap.jpg

https://pro-api.coinmarketcap.com/v1

在前端中有一个显示币价的功能,那么就要实时查询到这个币价。因为平时也是用coinmarketcap查看行情的,所以,第一时间也是想到用它来实现这个功能。

https://coinmarketcap.com/api/documentation/v1/#section/Standards-and-Conventions

先找来它的开发文档,注册帐号,获得API KEY,然后是测试查询!

this.axios.request({
    method:"get",
    url:'https://pro-api.coinmarketcap.com/v1/global-metrics/quotes/latest',
    headers: {
        'X-CMC_PRO_API_KEY': 'd8002bdd-7a6d-4a2b-xxxxx,
        "Accept": "application/json",
        "Access-Control-Allow-Origin":"*",
        "Content-Type":"application/json",
        "Accept-Encoding": "gzip",
    },
    params: {
        'CMC_PRO_API_KEY': 'd8002bdd-7a6d-4a2b-xxxxx',
    }
}).then( (arg) => {
    console.log(111,arg.data)
}).catch( (error) => {
    console.log(333,error)
})

按照文档写了函数,但测试起来总是有个跨域的问题存在,如上图所示!

以前做前端的时候也碰到过跨域的问题,调下参数一般都能解决!但这次的问题很怪:直接用postman都可以访问到数据,但用前端就是一直报错! 查了无数文档,看了数个视频,自信对跨域的问题是有了一定的了解,但是测试起来问题总是存在!

无奈下,只能求助于其它的API工具了,希望它能给我受伤的小心灵一点安慰吧!

coingecko.jpg

https://api.coingecko.com/api

async testApi(){
    let res = await this.axios.request({
        method:"get",
        url:'https://api.coingecko.com/api/v3/coins/bitcoin',
        headers: {
            "accept": "application/json",
        }
    })
    console.log(111,res)
}

这次换了coingecko的API,想不到一次就成功了,而且不用注册,也不用什么API KEY之类的,简短两行代码就搞定了,真是幸福感满满啊!

有时候还真不能钻牛角尖,特别是死牛角!换个思路可能会是更好的办法!

Leave 在前端中查询币价 / 网络研习社#74 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #cn posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang