You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用CoinGecko API遇404错误:提示‘Collection v3 not found’求助

解决CoinGecko API请求404错误(Collection 'v3' not found)

问题详情

我通过Angular的HttpClient发送GET请求从CoinGecko API拉取比特币价格,使用的API地址为https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd,但返回状态码404错误,响应体提示“Collection 'v3' not found”。

服务类代码

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    Authorization: 'my-auth-token'
  })
};
constructor(private http: HttpClient) { }

api: string = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd';

getCoinData(): Observable<Coin[]> {
  return this.http.get<Coin[]>(this.api, httpOptions);
}

组件TS文件代码

constructor(private cryptoCoinService : CryptoCoinsService) { }

ngOnInit(): void {
  this.getTopCoins();
}

getTopCoins() {
  this.cryptoCoinService.getCoinData()
    .subscribe(data => {
      this.topCoins = data;
    },
    err => console.log(err));
}

预期返回数据格式

{
  "bitcoin": {
    "usd": 17274.17
  }
}

问题原因与解决方案

核心问题

404错误的直接原因是多余的请求头导致API服务器错误解析请求路径:

  • CoinGecko的公开GET接口不需要Content-Type: application/json头(GET请求无请求体,该头完全多余)。
  • 公开API无需Authorization令牌,多余的认证头会干扰服务器对请求路径的解析逻辑。

此外代码还存在类型定义不匹配问题:预期返回的是单个键值对对象,而非Coin[]数组,类型错误会导致后续数据处理异常。

修正步骤

  1. 移除不必要的请求头:直接删除httpOptions(公开API不需要额外请求头)。
  2. 修正返回类型:将返回类型从Observable<Coin[]>改为与预期数据匹配的对象类型。

修正后的代码

服务类代码

constructor(private http: HttpClient) { }

api: string = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd';

// 定义与返回数据结构匹配的类型
getCoinData(): Observable<{ [key: string]: { usd: number } }> {
  return this.http.get<{ [key: string]: { usd: number } }>(this.api);
}

组件TS文件代码

// 定义匹配的变量类型
topCoins: { [key: string]: { usd: number } } = {};

constructor(private cryptoCoinService : CryptoCoinsService) { }

ngOnInit(): void {
  this.getTopCoins();
}

getTopCoins() {
  this.cryptoCoinService.getCoinData()
    .subscribe(data => {
      this.topCoins = data;
      console.log('比特币当前价格:', data.bitcoin.usd);
    },
    err => console.log(err));
}

验证结果

修改后重新发送请求,即可正常获取CoinGecko返回的比特币价格数据,404错误会被解决。

内容的提问来源于stack exchange,提问作者Marrs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:51:09