使用Web3.js实例化合约时出现TypeError: Cannot read properties of undefined (reading 'eth')错误
解决Web3.js合约实例化时的"Cannot read properties of undefined (reading 'eth')"错误
这个错误的核心原因是你直接使用了未初始化的web3对象,没有先创建Web3实例并连接到以太坊节点。以下是具体修复步骤:
首先确保正确导入Web3库,然后初始化web3实例:
import Web3 from 'web3'; import ElectionFactory from './Build/ElectionFact.json'; // 初始化web3实例:优先用浏览器钱包(如MetaMask)提供的provider, fallback到本地Ganache节点 const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545'); // 现在可以正常实例化合约 const instance = new web3.eth.Contract( JSON.parse(ElectionFactory.interface), '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' );如果是Node.js环境(而非浏览器),导入方式需调整为CommonJS格式:
const Web3 = require('web3'); const ElectionFactory = require('./Build/ElectionFact.json'); const web3 = new Web3('http://localhost:7545');验证web3实例是否正常创建:可以添加
console.log(web3)查看输出,如果结果是undefined,要检查节点连接地址是否正确,浏览器环境下确认钱包已授权并连接到对应网络。
内容的提问来源于stack exchange,提问作者VANSH SHAH
相关产品推荐
相关产品推荐

