I am fairly new to DAPP and I am trying to follow an online guide building my first smart contract. Here's the source code:
Election.sol
pragma solidity ^0.4.2;
contract Election {
string public candidateName;
constructor (string _candidateName) public {
candidateName = _candidateName;
}
function setCandidate (string _name) public {
candidateName = _name;
}
}
I've deployed to to my local Ganache (latest version on windows 10) and tried to interact with it using the Web3.js from here.
Here's my JavaScript code for my client side:
// Initialise web3
if (typeof web3 !== "undefined") {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
}
// Set account
web3.eth.defaultAccount = web3.eth.accounts[0];
// Set contract abi
var contractAbi = [ ... my aib here ... ];
// Set contract address
var contractAddress = "my-contract-address-here";
// Load the contract
var contract = web3.eth.contract(contractAbi).at(contractAddress);
// Display current candidate name
contract.candidateName(function(err, candidateName) {
if (err) {
alert("Error: " + err);
} else {
$("#canidateName").val(candidateName);
}
});
// Handle candidate name update
$("#updateCandidate").on("click", function(event) {
event.preventDefault();
contract.setCandidate($("#canidateName").val());
});
When I run my app in the browser, I am getting the following error:
web3.min.js:1 Failed to load http://localhost:7545/: Response to
preflight request doesn't pass access control check: The value of the
'Access-Control-Allow-Origin' header in the response must not be the
wildcard '*' when the request's credentials mode is 'include'. Origin
'null' is therefore not allowed access. The credentials mode of
requests initiated by the XMLHttpRequest is controlled by the
withCredentials attribute.Uncaught Error: CONNECTION ERROR: Couldn't connect to node
http://localhost:7545.
at Object.InvalidConnection (web3.min.js:1)
at t.send (web3.min.js:1)
at n.send (web3.min.js:1)
at l.accounts (web3.min.js:1)
at script.js:9 InvalidConnection @ web3.min.js:1 t.send @ web3.min.js:1 n.send @ web3.min.js:1 (anonymous) @ web3.min.js:1
(anonymous) @ script.js:9
Any idea what I might be doing wrong here?
Best Answer
I think I've worked out what the problem is.
Since my "client" doesn't technically need a webserver, I ran my html app directly from my desktop, i.e. it was executing from this url in chrome:
file:///C:/Users/Latheesan/Desktop/Crypto%20Election/index.html
After I moved it into a local webserver (e.g. apache) and running it from this url:
http://localhost/Crypto%20Election/
It's now working, I am no longer getting CORS errors.