[error saying web3 is not defined][1]<script>
var myContract;
async function CheckMetamaskConnection() {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
return true;
} catch (error) {
// User denied account access...
return false;
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
return true;
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
return false;
}
}
$(document).ready(async function () {
var IsMetamask = await CheckMetamaskConnection();
if (IsMetamask) {
myContract = await web3.eth.contract(SmartContractABI).at(SmartContractAddress);
getCandidate(1);
getCandidate(2);
await myContract.eventVote({
fromBlock:0
}, function(err, event){
console.log("event :", event);
getCandidate(event.args._candidateid.toNumber());
});
console.log("myContract :", myContract);
console.log("Metamask detected!")
} else {
console.log("Metamask not detected");
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Metamask not detected!',
onClose() {
location.reload();
}
});
}
});
async function getCandidate(cad){
await myContract.candidates(cad, function(err, result){
if (!err) {
console.log("result : ", result);
document.getElementById("cad" + cad).innerHTML = result[1];
document.getElementById("cad"+cad+'count').innerHTML = result[2].toNumber();
}
});
}
async function Vote(cad){
await myContract.vote(cad, function(err, result){
if(!err){
console.log("We are winning!");
} else{
console.log("Can not connect to the smart contract");
}
})
}
</script>`我在我的系统(Windows10)中有node.js和metamask,我从github克隆了你的项目,并通过以下命令运行它
npm install node index.js UI在localhost:3000中完美部署,但当我尝试投票时,事务不工作!然后我看到智能合约上的内容没有渲染!然后我检查了metamask,它是连接的,并且在ropsten网络上有一个以太网!然后我尝试了ganache (本地区块链提供商),但事务仍然不工作!然后我将智能合约粘贴到remix中,并获得ABI和智能合约地址,但仍然不起作用!然后我转到浏览器的开发者工具,看到下面的错误!...i对这个错误一无所知!...how我能解决这个问题吗?
发布于 2021-03-27 07:10:49
错误可能是由于加载Web3而发生的。请尝试此函数:
async loadWeb3(){
if(window.ethereum){
window.web3 = new Web3(window.ethereum)
await window.ethereum.request({ method: 'eth_requestAccounts' })
}
else if(window.web3){
window.web3 = new Web3(window.ethereum)
}
else{
window.alert("Non-Ethereum browser detected. You should consider trying MetaMask!")
}}
另外,不要忘记在javascript类中添加导入:
import Web3 from 'web3'并使用npm安装导入:
npm i web3 --savehttps://stackoverflow.com/questions/65932405
复制相似问题