Etherscan API在JavaScript中返回以太坊余额为0的问题排查
问题排查与修复
首先看你的JavaScript代码里的API请求URL,参数拼接存在语法错误:
你写的URL片段是:
"https://api.etherscan.io/api?module=account&action=balance&address="+address +"tag=latest&apikey=RE98FGG6WVI25619AZKGI6B9IPJS6I64N8"
这里的address="+address +"tag=latest部分,缺少了参数分隔符&,导致tag=latest被直接拼接到地址后面,变成了无效的钱包地址,Etherscan找不到对应地址的余额,所以返回result: "0"。
修复后的代码
把URL里的参数拼接修正,在address和tag之间加上&:
let ether = { fetchEther: function(address) { fetch("https://api.etherscan.io/api?module=account&action=balance&address=" + address + "&tag=latest&apikey=RE98FGG6WVI25619AZKGI6B9IPJS6I64N8") .then((response) => response.json()) .then((data) => this.displayBalance(data)); }, displayBalance: function(data) { const { result } = data; // 可选:将wei转换为ETH(1 ETH = 1e18 wei) const ethBalance = parseInt(result) / 1e18; console.log("Wei余额:", result); console.log("ETH余额:", ethBalance); } }
额外检查点
- 确认你的API密钥是有效的,没有超过调用次数限制
- 钱包地址格式正确(你提供的地址
0x00000000219ab540356cBB839Cbe05303d7705Fa是合法的) - Etherscan API返回的
result单位是wei,需要除以1e18才能得到ETH单位的余额
内容的提问来源于stack exchange,提问作者mintgg
相关产品推荐
相关产品推荐

