我正在尝试按照此 example 构建一个可以与智能合约交互的网页。 它在混音中使用此代码:
pragma solidity ^0.4.18;
contract Coursetro {
string fName;
uint age;
function setInstructor(string _fName, uint _age) public {
fName = _fName;
age = _age;
}
function getInstructor() public constant returns (string, uint) {
return (fName, age);
}
}
我在visual studio代码中设置的这段代码:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="main.css">
<!-- <script src="./node_modules/web3/dist/web3.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.36/dist/web3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Coursetro Instructor</h1>
<h2 id="instructor"></h2>
<label for="name" class="col-lg-2 control-label">Instructor Name</label>
<input id="name" type="text">
<label for="name" class="col-lg-2 control-label">Instructor Age</label>
<input id="age" type="text">
<button id="button">Update Instructor</button>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
web3.eth.defaultAccount = web3.eth.accounts[0];
var CoursetroContract = web3.eth.contract([
{
"constant": false,
"inputs": [
{
"name": "_fName",
"type": "string"
},
{
"name": "_age",
"type": "uint256"
}
],
"name": "setInstructor",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getInstructor",
"outputs": [
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]);
var Coursetro = CoursetroContract.at('0x0CF6A859635A0729d14b524d05619c7162A102bd');
console.log(Coursetro);
Coursetro.getInstructor(function(error, result){
if(!error)
{
$("#instructor").html(result[0]+' ('+result[1]+' years old)');
console.log(result);
}
else
console.error(error);
});
$("#button").click(function() {
Coursetro.setInstructor($("#name").val(), $("#age").val());
});
</script>
</body>
</html>
当我尝试在本地主机上拉起它时,我已经设置了它。 localhost:8545,它在控制台中给了我一个 400 Bad Request:
所以我尝试使用 http-server 命令成功设置了一个我可以访问的站点,但是我在控制台中收到这些错误:
只是想知道是否有人以前遇到过这个问题并且知道如何解决这些问题?或者如果我遗漏了什么,这就是我收到错误的原因。