问题描述
我实际上是在尝试编写一个简单的前端智能合约,它从用户那里获取一个值并将其保存在智能合约的变量中。 我项目的 index.html 部分是
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="utf-8">
<Meta http-equiv="X-UA-Compatible" content="IE=edge">
<Meta name="viewport" content="width=device-width,initial-scale=1">
<title>Example</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="message"></div>
<form method="POST">
<div><input id= "message" name = "message" type= "text">
</div>
<div>
<button type="button" id="register">Register</button>
</div>
</div>
</form>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
app.js 是
App = {
web3Provider: null,contracts: {},account: '0x0',init: function() {
return App.initWeb3();
},initWeb3: function() {
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},initContract: function() {
$.getJSON("HelloWorld.json",function(hello) {
// Instantiate a new truffle contract from the artifact
App.contracts.HelloWorld = TruffleContract(hello);
// Connect provider to interact with contract
App.contracts.HelloWorld.setProvider(App.web3Provider);
return App.bindEvents();
});
},bindEvents: function() {
$(document).on('click','#register',function(){ var msg = $('#message').val(); App.handleMessage(msg); });
},handleMessage: function(msg){
var hwinstance;
App.contracts.HelloWorld.deployed().then(function(instance) {
hwinstance = instance;
return hwinstance.setMessage(msg);
}).then( function(result){
if(result.receipt.status == '0x01')
alert("successfully")
else
alert("Failed due to revert")
}).catch( function(err){
alert("Failed")
})
}
};
$(function() {
$(window).load(function() {
App.init();
console.log('starting app.js');
});
});
我写的智能合约代码是
pragma solidity 0.5.16;
contract HelloWorld {
string private message = "hello world";
function getMessage() public view returns(string memory) {
return message;
}
function setMessage(string memory newMessage) public {
message = newMessage;
}
}
当我运行命令 truffle complie 和 truffle migrate 时,它没有显示任何错误,但是当我运行“npm run dev”时,页面显示“无法获取 /”。
我无法理解错误在哪里。请帮忙!
是否有其他方式将前端连接到智能合约?
解决方法
您的本地服务器无法找到您的页面,因为它位于错误的目录中或本地服务器尚未安装。运行npm install --save-dev lite-server
。在 package.json 你应该有类似
"script": {
"dev": "lite-server",...
}
将您的 index.html 和 App.js 移动到您在项目根目录下创建的 src/
目录中。运行 npm run dev
再次检查。它应该工作。如果你对一个易于使用的带有 React 的松露盒感兴趣,我已经开发了一个带有 React + Material-UI 的松露盒。看看这里https://github.com/rouftom/truffle-react-material