You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

请求协助修改Node.js代码:将Binance API结果在本地网页展示

把Binance API数据展示在本地网页的完整方案

嘿,我来帮你一步步搞定这个需求!作为新手,用Express框架来搭本地服务器是最简单的选择,下面我会把完整的代码和步骤都写清楚,你跟着做就行~

第一步:准备依赖

首先,你需要安装两个必要的npm包:

  • express:Node.js最常用的轻量web框架,用来搭建本地服务器
  • node-binance-api:你原来用的Binance API调用工具

打开终端,进入你的项目文件夹,执行下面的命令:

npm install express node-binance-api

方案一:服务器直接生成HTML(最简单,适合快速上手)

创建一个名为server.js的文件,把下面的代码复制进去:

// 引入需要的模块
const express = require('express');
const binance = require('node-binance-api');

// 初始化Express服务器
const app = express();
const port = 3000; // 本地服务器的端口号,3000是常用的,你也可以改成其他数字

// 创建首页路由:当用户访问http://localhost:3000时触发
app.get('/', (req, res) => {
    // 调用Binance API获取价格数据
    binance.prices(function(error, ticker) {
        // 处理错误情况
        if (error) {
            res.send(`<h1>获取数据失败</h1><p>错误信息:${error.message}</p>`);
            return;
        }

        // 把价格数据转换成HTML列表
        let priceList = '<ul>';
        for (let symbol in ticker) {
            priceList += `<li>${symbol}: ${ticker[symbol]}</li>`;
        }
        priceList += '</ul>';

        // 生成完整的HTML页面
        const htmlPage = `
            <!DOCTYPE html>
            <html>
                <head>
                    <title>Binance 实时价格</title>
                    <style>
                        body { font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto; padding: 0 20px; }
                        h1 { color: #2c3e50; }
                        ul { list-style: none; padding: 0; }
                        li { padding: 8px; border-bottom: 1px solid #eee; }
                    </style>
                </head>
                <body>
                    <h1>Binance 加密货币实时价格</h1>
                    ${priceList}
                </body>
            </html>
        `;

        // 把HTML页面发送给浏览器
        res.send(htmlPage);
    });
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器已经启动啦!你可以在浏览器访问:http://localhost:${port}`);
});

运行方式:

  1. 在终端执行:node server.js
  2. 打开浏览器,输入http://localhost:3000,就能看到Binance的实时价格列表了!

方案二:前后端分离(适合后续扩展,比如定时刷新)

这个方案里,后端负责提供API接口返回JSON数据,前端负责展示和刷新数据,更灵活。

第一步:修改server.js

const express = require('express');
const binance = require('node-binance-api');

const app = express();
const port = 3000;

// 告诉Express可以读取public文件夹里的静态文件(比如HTML、CSS、JS)
app.use(express.static('public'));

// 创建API接口:返回Binance价格的JSON数据
app.get('/api/prices', (req, res) => {
    binance.prices(function(error, ticker) {
        if (error) {
            // 返回错误状态码和错误信息
            res.status(500).json({ error: error.message });
            return;
        }
        // 返回价格数据的JSON
        res.json(ticker);
    });
});

app.listen(port, () => {
    console.log(`服务器已启动!访问http://localhost:${port}查看页面`);
});

第二步:创建前端HTML文件

在项目文件夹里新建一个public文件夹,然后在里面创建index.html文件:

<!DOCTYPE html>
<html>
<head>
    <title>Binance 实时价格</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto; padding: 0 20px; }
        h1 { color: #2c3e50; }
        ul { list-style: none; padding: 0; }
        li { padding: 8px; border-bottom: 1px solid #eee; }
        .refresh-btn { 
            padding: 10px 20px; 
            background: #3498db; 
            color: white; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer; 
            margin-bottom: 20px;
        }
        .refresh-btn:hover { background: #2980b9; }
    </style>
</head>
<body>
    <h1>Binance 加密货币实时价格</h1>
    <button class="refresh-btn" onclick="loadPrices()">手动刷新价格</button>
    <ul id="price-list"></ul>

    <script>
        // 页面加载完成后自动获取数据
        window.onload = loadPrices;

        // 获取价格数据并渲染到页面
        function loadPrices() {
            fetch('/api/prices')
                .then(response => response.json())
                .then(tickerData => {
                    const priceListElement = document.getElementById('price-list');
                    priceListElement.innerHTML = ''; // 清空旧数据

                    // 遍历价格数据,生成列表项
                    for (let symbol in tickerData) {
                        const listItem = document.createElement('li');
                        listItem.textContent = `${symbol}: ${tickerData[symbol]}`;
                        priceListElement.appendChild(listItem);
                    }
                })
                .catch(error => {
                    alert('获取数据失败:' + error.message);
                });
        }

        // 可选:每30秒自动刷新一次数据
        setInterval(loadPrices, 30000);
    </script>
</body>
</html>

运行方式和方案一一样:

  1. 终端执行node server.js
  2. 浏览器访问http://localhost:3000,就能看到带刷新按钮的页面,还会自动每30秒更新一次价格!

小提示

  • 如果遇到API请求失败,大概率是网络问题或者Binance的访问限制,代码里已经做了错误处理,会显示错误信息
  • 端口号如果被占用,可以把port变量改成其他数字,比如3001

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

火山引擎 最新活动