5 使用web3.js获取区块链上的数据提示获取不到链

import Web3 from "web3";
import votingCoinArtifact from "../../build/contracts/Voting.json";//导入solidity编码后的内容
const ainBytes32="0x41000000000000000000000000000000000000000000000000000000000000";//2个传参过来的值 A
const binBytes32="0x42000000000000000000000000000000000000000000000000000000000000";//2个传参过来的值 B
//var infoContract=web3.get.account[0];
//onsole.log(infoContract);
const App = {
  web3: null,
  account: null,
   voting: null,
//启动的时候调用的函数
  start: async function() {
    const { web3 } = this;

    try {
      //这里代码有问题      
      // get contract instance
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = votingCoinArtifact.networks[networkId];
      this.voting = new web3.eth.Contract(
        votingCoinArtifact.abi,
        deployedNetwork.address,

      );

      // get accounts
   //   const accounts = await web3.eth.getAccounts();
     // this.account = accounts[0];
 // this.ready();

    } catch (error) {
      console.error("Could not connect to contract or chain.11");
    }
  },

  refresh:async function(id,nameInBytes32){
    const{totalVotesFor}=this.Voting.methods;
    const tickets=await totalVotesFor(nameInBytes32).call();//获取区块链上的值
    const element=document.getElementById(id);
    element.innerHTML=tickets.toString();

  },

  //异步函数
  voteForCandidate:async function(){
 try{
   const{voteForCandidate}=this.Voting.methods;//

   const candidateName=document.getElementById("canditate").value;//获得html中id为canditate的值

   if(candidateName=="Alcie"){
  await voteForCandidate(ainBytes32).send({from:this.account});
  this.refresh("alice",ainBytes32);
   }else if(candidateName=="Bon"){
    await voteForCandidate(binBytes32).send({from:this.account});
    this.refresh("Bon",binBytes32);
   }

 }
 catch(err){
   console.log(err);
 }
}

};

window.App = App;

window.addEventListener("load", function() {
  if (window.ethereum) {
    // use MetaMask's provider

    App.web3 = new Web3(window.ethereum);
    window.ethereum.enable(); // get permission to access accounts
  } else {
    console.warn(
      "No web3 detected. Falling back to https://127.0.0.1:8545. You should remove this fallback when you deploy live",
    );
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    App.web3 = new Web3(
      new Web3.providers.HttpProvider("https://127.0.0.1:8545"),
    );
  }

  App.start();
});

image.png

请先 登录 后评论

1 个回答

Tiny熊 - 布道者
  擅长:智能合约,以太坊
请先 登录 后评论