如何从CoinGecko API的JSON响应取值并赋值给JS常量rate?
解决从CoinGecko API提取价格数据到JavaScript常量的问题
你的代码核心错误在于对fetch响应解析后的对象理解有误:
res.json()已经将API返回的JSON字符串解析成了JavaScript对象,这个对象里没有responseText属性(responseText是传统XMLHttpRequest的属性,fetch的响应对象不适用)。- CoinGecko的
/simple/price接口返回的结构是{ "币种id": { "目标币种": 价格数值 } },比如请求ids=bitcoin&vs_currencies=usd时,返回的是{"bitcoin":{"usd":60000}}。
所以正确提取价格并赋值给rate常量的方式是使用方括号访问对象属性:const rate = data[give][get];
修正后的完整代码如下:
fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${give}&vs_currencies=${get}`) .then(res => res.json()) .then((data) => { const rate = data[give][get]; rateE1.innerText = `1 ${give} = ${rate} ${get}`; get_qty_enter.value = (give_qty_enter.value * rate).toFixed(5); }) .catch(err => console.error(err));
另外补充两点注意事项:
- 要确保
give和get变量的值与CoinGecko API要求的币种id/代码完全一致(比如bitcoin而非BTC,usd而非USD),否则会出现undefined错误。 - 可以在代码中加入异常判断,比如检查
data[give]和data[give][get]是否存在,避免因API返回结构变化或参数错误导致的程序崩溃。
内容的提问来源于stack exchange,提问作者Muhammad Ahmad
相关产品推荐
相关产品推荐

