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

如何基于NodeJS、Express构建API获取加密货币实时价格

Solution: Fetching Real-Time Crypto Prices for Your Node.js/Express API

Hey there! Let's tackle this problem step by step—getting real-time crypto prices into your Express API is totally doable with public crypto APIs, and I'll walk you through how to integrate one smoothly. Here's a practical approach using a free, easy-to-use API and integrating it with your existing Express setup:

Step 1: Pick a Free Public Crypto API

Most crypto platforms offer free tiers for price data. A great beginner-friendly option is CoinGecko's API (no API key required for basic endpoints), which supports BTC, LTC, ETH, BCH and thousands of other coins.

Step 2: Use an HTTP Client to Fetch Data

You can use Node.js's built-in fetch (available in Node 18+) or a popular library like axios to make requests to the API. Let's go with axios for simplicity.

First, install it in your project:

npm install axios

Step 3: Integrate the Price Fetch into Your Express Routes

Here's how to set up a dynamic route that accepts a coin symbol (like BTC) and returns its current price:

const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;

// Dynamic route for crypto prices
app.get('/:coin', async (req, res) => {
  try {
    const coinSymbol = req.params.coin.toLowerCase();
    // Map your supported symbols to CoinGecko's coin IDs (they use slugs, not always symbols)
    const coinIdMap = {
      btc: 'bitcoin',
      ltc: 'litecoin',
      eth: 'ethereum',
      bch: 'bitcoin-cash'
    };

    const coinId = coinIdMap[coinSymbol];
    if (!coinId) {
      return res.status(400).json({ error: 'Unsupported cryptocurrency symbol' });
    }

    // Fetch current price from CoinGecko
    const response = await axios.get(`https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd`);
    
    const price = response.data[coinId]?.usd;
    if (!price) {
      return res.status(500).json({ error: 'Failed to retrieve price data' });
    }

    // Return the price (you can also save this to MongoDB if you want to track historical data)
    res.json({
      symbol: coinSymbol.toUpperCase(),
      price_usd: price,
      last_updated: new Date().toISOString()
    });
  } catch (error) {
    console.error('Error fetching crypto price:', error.message);
    res.status(500).json({ error: 'Internal server error while fetching price' });
  }
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

To avoid hitting the external API on every request (which can get rate-limited and slow down your API), add caching. You can use node-cache for in-memory caching:

Install it:

npm install node-cache

Update your code to include caching:

const NodeCache = require('node-cache');
const priceCache = new NodeCache({ stdTTL: 60 }); // Cache for 60 seconds

// Inside your route handler:
app.get('/:coin', async (req, res) => {
  try {
    const coinSymbol = req.params.coin.toLowerCase();
    const coinIdMap = { /* ... same as before ... */ };
    const coinId = coinIdMap[coinSymbol];

    if (!coinId) {
      return res.status(400).json({ error: 'Unsupported cryptocurrency symbol' });
    }

    // Check cache first
    const cachedPrice = priceCache.get(coinSymbol);
    if (cachedPrice) {
      return res.json({
        symbol: coinSymbol.toUpperCase(),
        price_usd: cachedPrice,
        last_updated: new Date().toISOString(),
        source: 'cache'
      });
    }

    // Fetch from API if not cached
    const response = await axios.get(`https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd`);
    const price = response.data[coinId]?.usd;

    if (!price) {
      return res.status(500).json({ error: 'Failed to retrieve price data' });
    }

    // Save to cache
    priceCache.set(coinSymbol, price);

    res.json({
      symbol: coinSymbol.toUpperCase(),
      price_usd: price,
      last_updated: new Date().toISOString(),
      source: 'api'
    });
  } catch (error) {
    console.error('Error fetching crypto price:', error.message);
    res.status(500).json({ error: 'Internal server error while fetching price' });
  }
});

Step 5: Test with Postman

Now fire up your server, send a GET request to http://localhost:3000/BTC (or any of your supported coins), and you should get the current USD price in the response!

Notes:

  • If you want to use a different API (like CoinMarketCap), you'll need to sign up for a free API key and adjust the endpoint/request parameters accordingly.
  • If you want to store historical prices in MongoDB, you can add a Mongoose schema for crypto prices and save the data to your database every time you fetch from the API (or on a schedule with something like node-schedule).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:19:09