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

运行Solana getBalance示例始终报错,求解决方法

Solana JS程序运行fetch失败问题排查与解决

问题场景

使用以下Solana查询余额的JS代码:

import { Connection, LAMPORTS_PER_SOL, PublicKey, clusterApiUrl  } from "@solana/web3.js";
const connection = new Connection("https://api.devnet.solana.com", "confirmed");

const publicKey = new PublicKey('dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8');

const balanceInLamports = await connection.getBalance(publicKey);

const balanceInSOL = balanceInLamports / LAMPORTS_PER_SOL;

console.log(
    `💰 Finished! The balance for the wallet at address ${publicKey} is ${balanceInSOL}!`
);

运行时无论用node balance.js还是npx esrun balance.ts,均返回TypeError: fetch failed错误,但系统已配置代理,且Solana命令行工具可正常连接网络。

解决方案

1. 为Node.js配置代理环境变量

Node.js默认不会自动读取系统代理,需手动设置环境变量后再运行程序:

  • Windows CMD:
    set HTTP_PROXY=http://你的代理地址:端口
    set HTTPS_PROXY=http://你的代理地址:端口
    node balance.js
    
  • Windows PowerShell:
    $env:HTTP_PROXY="http://你的代理地址:端口"
    $env:HTTPS_PROXY="http://你的代理地址:端口"
    node balance.js
    
  • Linux/macOS:
    export HTTP_PROXY=http://你的代理地址:端口
    export HTTPS_PROXY=http://你的代理地址:端口
    node balance.js
    

2. 在代码中显式配置代理

通过修改Connection的fetch选项,强制使用指定代理:
首先安装依赖:

npm install node-fetch https-proxy-agent

修改后的代码:

import { Connection, LAMPORTS_PER_SOL, PublicKey, clusterApiUrl } from "@solana/web3.js";
import fetch from 'node-fetch';
import HttpsProxyAgent from 'https-proxy-agent';

// 替换为你的代理地址
const proxyAgent = new HttpsProxyAgent('http://你的代理地址:端口');

const connection = new Connection(clusterApiUrl('devnet'), {
  commitment: 'confirmed',
  fetch: (url, options) => fetch(url, { ...options, agent: proxyAgent })
});

const publicKey = new PublicKey('dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8');

const balanceInLamports = await connection.getBalance(publicKey);
const balanceInSOL = balanceInLamports / LAMPORTS_PER_SOL;

console.log(
    `💰 Finished! The balance for the wallet at address ${publicKey} is ${balanceInSOL}!`
);

如果代理需要用户名密码认证,修改代理地址为:

const proxyAgent = new HttpsProxyAgent('http://用户名:密码@你的代理地址:端口');

3. 切换到本地Solana测试节点

启动本地devnet节点,完全绕开外部网络代理问题:

solana-test-validator

修改代码中的连接地址为本地节点:

const connection = new Connection("http://localhost:8899", "confirmed");

再次运行程序即可正常查询。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:45:12