以太坊Dapp开发通过web3.js调用智能合约

在dapp目录下创建一个工程sixtest

在dapp目录下创建一个工程sixtest

[root@ dapp]# express -e sixtest

我们在remix当中部署好的智能合约

pragma solidity ^0.4.22;contract  counter{    uint256 counter;    constructor() public{        counter = 1;    }    function getCounter()public view returns(uint256){        return counter;    }    function changeCounter(uint256 a) public{        counter += a;    }}

以太坊Dapp开发通过web3.js调用智能合约以太坊Dapp开发通过web3.js调用智能合约

进入到sixtest目录下进行npm install操作

我们还需要进行安装web3

npm install web3 -save

修改routes目录下的index.js

var express = require(\'express\');var router = express.Router();var Web3 = require(\'web3\');var web3 =  new Web3(new Web3.providers.HttpProvider(\'http://localhost:8545\'));web3.getAccounts().then(console.log);/* GET home page. */router.get(\'/\', function(req, res, next) {  res.render(\'index\', { title: \'Express\' });});module.exports = router;              

修改目录下的app.js文件 vim app.js

var createError = require(\'http-errors\');var express = require(\'express\');var path = require(\'path\');var cookieParser = require(\'cookie-parser\');var logger = require(\'morgan\');var indexRouter = require(\'./routes/index\');var usersRouter = require(\'./routes/users\');var app = express();var ejs = require(\'ejs\');// view engine setupapp.set(\'views\', path.join(__dirname, \'views\'));app.engine(\'.html\',ejs.__express);app.set(\'view engine\', \'html\');//app.set(\'view engine\', \'ejs\');app.use(logger(\'dev\'));app.use(express.json());app.use(express.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, \'public\')));app.use(\'/\', indexRouter);app.use(\'/users\', usersRouter);// catch 404 and forward to error handlerapp.use(function(req, res, next) {  next(createError(404));});// error handlerapp.use(function(err, req, res, next) {  // set locals, only providing error in development  res.locals.message = err.message;  res.locals.error = req.app.get(\'env\') === \'development\' ? err : {};  // render the error page  res.status(err.status || 500);  res.render(\'error\');module.exports = app;

在sixtest目录下的views当中创建index.html文件,并且将index.ejs复制到其中。

                  

Welcome to

测试是否能成功

[root@ sixtest]# npm start> sixtest@0.0.0 start> node ./bin/www[  \'0x930518c17201051A2C9a820c242F205f87767f06\',  \'0x652945236a3d96e631f95c9373Fc5d0774Ae2e92\',  \'0xbf4f91f8D7cb564e6d016DDA6a65BC5eDbacf902\',  \'0xD79a65Dc80bE92625D739e7daC05a361D9BeaF9E\',  \'0x8544049B57803e0a190445F268Fb3e7A3D307cED\',  \'0xb1a518Ca38F9532230ae982703eEC3844249E772\',  \'0xb24aCF61a30bcb618da8e27E57eC5167892E21A1\',  \'0xf02cFF084d416CD89057a067385ee8312DB51022\',  \'0x52B8600BB62938Fc461006BdE4a3c34A2914c5A4\',  \'0xBc07537f4E016FB3341728390285D271fefB48ce\']

证明成功连上web3.js

现在进一步修改routes当中的index.js文件

ar express = require(\'express\');var router = express.Router();var Web3 = require(\'web3\');var web3 =  new Web3(new Web3.providers.HttpProvider(\'http://localhost:8545\'));// web3.eth.getAccounts().then(console.log);var myContract = new web3.eth.Contract([        {                \"constant\": false,                \"inputs\": [                        {                                \"name\": \"a\",                                \"type\": \"uint256\"                        }                ],                \"name\": \"changeCounter\",                \"outputs\": [],                \"payable\": false,                \"stateMutability\": \"nonpayable\",                \"type\": \"function\"                        },        {                \"inputs\": [],                \"payable\": false,                \"stateMutability\": \"nonpayable\",                \"type\": \"constructor\"        },        {                \"constant\": true,                \"inputs\": [],                \"name\": \"getCounter\",                \"outputs\": [                        {                                \"name\": \"\",                                \"type\": \"uint256\"                        }                ],                \"payable\": false,                \"stateMutability\": \"view\",                \"type\": \"function\"        }], \'0x2247fdbC867ab4A6fb85787Daa0c12B9aB27FB60\');//myContract.methods.getCounter().call({from: \'0x652945236a3d96e631f95c9373Fc5d0774Ae2e92\'}, function(error, result){//     console.log(\"counter:\",result);//});var init_counter = 0;var current_counter = 0;myContract.methods.getCounter().call().then(function(counter){     console.log(\'init counter:\',counter);     init_counter = counter;});/* GET home page. */router.get(\'/\', function(req, res, next) {myContract.methods.changeCounter(5).send({from: \'0x652945236a3d96e631f95c9373Fc5d0774Ae2e92\'}).then(function(){     myContract.methods.getCounter().call().then(function(counter){     console.log(\'current counter:\',counter);     current_counter = counter;     res.render(\'index\', {init:init_counter,current:current_counter });        });   });});module.exports = router;

接下来我们来修改views当中的index.html

      调用智能合约            

init:

current:

最后我们来看一下效果
在sixtest目录下运行npm start命令
出现以下结果

[root@ sixtest]# npm start> sixtest@0.0.0 start> node ./bin/wwwinit counter: 21

此时在浏览器中打开http://127.0.0.1:3000以太坊Dapp开发通过web3.js调用智能合约此时也会出现我们的current

[root@ sixtest]# npm start> sixtest@0.0.0 start> node ./bin/wwwinit counter: 21current counter: 26GET / 200 196.958 ms - 213GET /stylesheets/style.css 304 204.034 ms - -

给TA打赏
共{{data.count}}人
人已打赏
区块链推广

“2021ISIG中国产业智能大会低代码峰会”即将开幕,钉钉宜搭叶周全受邀出席

2021-11-28 10:37:25

区块链推广

链游是什么?最近这个话题是最火的

2021-11-28 10:37:28

重要说明

本站资源大多来自网络,如有侵犯你的权益请联系管理员 区块链币  或给邮箱发送邮件834379394@qq.com 我们会第一时间进行审核删除。 站内资源为网友个人学习或测试研究使用,未经原版权作者许可,禁止用于任何商业途径!请在下载24小时内删除!


如果你遇到支付完成,找不到下载链接,或者不能下载,或者解压失败,先不要忙,加博主的QQ:834379394 (博主有可能有事情或者在睡觉不能及时的回复您,QQ留言后,请耐心等待即可!)

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索