使用Web3.js+Ganache获取账户余额时遇TypeError错误求助
问题解决:Web3.js调用getBalance报错TypeError
错误根源
你已经通过new Web3()创建了连接Ganache的实例ganacheWeb3,但后续调用getBalance时却直接使用Web3构造函数(大写的Web3),而非这个实例。Web3构造函数本身没有Eth或eth属性,因此触发了"Cannot read properties of undefined"的错误。
修正后的代码
Promise方式
var Web3 = require("web3"); // 连接Ganache节点 const ganacheWeb3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")); // 使用实例化后的ganacheWeb3调用getBalance const balanceOfAccount = ganacheWeb3.eth.getBalance("0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5"); balanceOfAccount.then((result) => { console.log(ganacheWeb3.utils.fromWei(result, "ether")); });
回调函数方式
var Web3 = require("web3"); // 连接Ganache节点 const ganacheWeb3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")); // 使用实例化后的ganacheWeb3调用getBalance ganacheWeb3.eth.getBalance( "0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5", (error, result) => { if (error) { console.log(error); } else { console.log(ganacheWeb3.utils.fromWei(result, "ether")); // 转换为ether单位更易读 } } );
关键注意事项
- 所有与节点交互的方法(比如
getBalance、utils.fromWei)都要通过实例化后的ganacheWeb3对象调用,不能直接用Web3构造函数。 - Web3.js中对应以太坊操作的属性是小写的
eth,你之前写的Web3.Eth(大写E)本身就是错误写法,正确的实例属性是ganacheWeb3.eth。
内容的提问来源于stack exchange,提问作者MSourav99
相关产品推荐
相关产品推荐

