接着上一步骤,继续开发
今天任务:
- 搭建node服务端
- 通过web3.js实现与以太坊的交互
- 安装节点工具Ganache,来搭建私有链节点
- 利用postman测试接口
目录结构:
搭建node服务端(server.js)
var http = require("http"); var url = require("url"); var querystring = require(‘querystring‘); function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; var body = ‘‘; //每当接收到请求体数据,累加到post中 request.on(‘data‘, function (chunk) { body += chunk; //一定要使用+=,如果body=chunk,因为请求favicon.ico,body会等于{} }); //async、await处理异步请求 request.on(‘end‘, async function () { // 解析参数 body = querystring.parse(body); //将一个字符串反序列化为一个对象 //返回json数据,并解决跨域问题 response.writeHead(200, { "Content-Type": "text/json","Access-Control-Allow-Origin":"*"}); var content = await route(handle, pathname, body); response.write(JSON.stringify(content)); response.end(); }); } http.createServer(onRequest).listen(9999); console.log("Server has started.."); } exports.start = start;
通过web3.js实现与以太坊的交互(requestHandler.js)
//测试 function test(body) { return ‘result‘; } //创建账户 async function newAccount(body) { var account = "account"; // console.log(body.password); await web3.eth.personal.newAccount(body.password, function (error, data) { console.log("创建的新账户地址:" + data) account = data; }); sendToAccount(account, ‘10‘); return account; } //转账给用户 async function sendToAccount(account, amount) { var result =await unlockAccount(adminAccount, adminPassword); if (result) {//解锁管理员账户 web3.eth.sendTransaction({ from: adminAccount, to: account, value: web3.utils.toWei(amount) }, function (error, data) { console.log("交易的hash值:" + data); }); } } //解锁账户 async function unlockAccount(account, password) { var result = false; await web3.eth.personal.unlockAccount(account, password, 300, function (error, data) { console.log(account + "解锁结果:" + data); result = data; }); return result; } //部署合约方法的转发,因为没有返回值,server.js中会报错 async function deploy(body) { var account = body.account; var password = body.password; console.log(account);
var address = await deployContract(account); console.log("address:"+address); return {‘contractAddress‘:address}; } //部署合约 function deployContract(account) { return new Promise(function (resolve, reject) { bn.deploy({ data: bytecode }).send({ from: account, gas: 3000000, gasPrice: ‘300000000000‘ }, function (error, data) { //data:交易的哈希值 console.log(error); console.log(data); }).on(‘receipt‘, function (receipt) { console.log(‘合约的地址:‘ + receipt.contractAddress) // contains the new contract address //contractAddress = receipt.contractAddress;//TODO 异步的问题 resolve(receipt.contractAddress); }); }); //return contractAddress; } //添加笔记 async function addNote(body) { var title = body.title; var desc = body.desc; var content = body.content; var account = body.account; var password = body.password; var date = getNowFormatDate(); var id = web3.utils.sha3(new Date().getTime() + title + desc + content); var contractAddress = body.contractAddress; var result = await unlockAccount(account, password); if (result) {//解锁当前用户的以太坊账户 bn.options.address = contractAddress; bn.methods.addNote(date, id, title, desc, content).send({ from: account }, function (error, data) { //data:调用方法之后的返回值 return ‘success‘; }); } } //获得笔记列表 async function getNoteList(body) { var date = body.date; var count = body.count; var account = body.account; var password = body.password; var contractAddress = body.contractAddress; var result = await unlockAccount(account, password); if (result) {//解锁当前用户的以太坊账户 bn.options.address = contractAddress; bn.methods.getNodeList(date, count).call({ from: account }, function (error, data) { //data:调用方法之后的返回值 }); } } //获得一个笔记 async function getNote(body) { var date = body.date; var id = body.id; var account = body.account; var password = body.password; var contractAddress = body.contractAddress; var result = await unlockAccount(account, password); if (result) {//解锁当前用户的以太坊账户 bn.options.address = contractAddress; bn.methods.getNode(date, id).call({ from: account }, function (error, data) { //data:调用方法之后的返回值 }); } } //获取当前时间,格式YYYY-MM-DD function getNowFormatDate() { var date = new Date(); var seperator1 = "-"; var year = date.getFullYear(); var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var currentdate = year + seperator1 + month + seperator1 + strDate; return currentdate; } exports.test = test; exports.newAccount = newAccount; exports.deploy = deploy; exports.addNote = addNote; exports.deployContract = deployContract;
安装节点工具Ganache,搭建私有链节点
传送门:https://truffleframework.com/ganache
ganache提供了10个测试账户,并且每个账户都有100个以太币,便于测试
这里我用第一个进行测试
首先,将web3请求的地址改为私有链节点的地址(requestHandle.js)
const web3 = new Web3(new Web3.providers.HttpProvider(‘http://127.0.0.1:7545‘));
私有链节点地址可以在ganache上方查看
启动node服务端
利用postman测试接口
测试test方法,返回"result",说明可以正常访问nodejs服务端。
其他方法陆续进行测试,这里就不多说明。