Development of cloud note applet based on blockchain

Continue with the previous step

 

 

Today's mission:

  • Build node server
  • Interaction with Ethereum through web3.js
  • Install the node tool Ganache to build a private chain node
  • Using postman to test interface

 

Directory structure:

 

Build node server (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 = '';
        //Every time the request body data is received, it is accumulated to post in
        request.on('data', function (chunk) {
            body += chunk;  //Be sure to use+=,If body=chunk,Because request favicon.ico,body Would be equal to{}
        });
        //async,await Processing asynchronous requests
        request.on('end', async function () {
            // Analytic parameter
            body = querystring.parse(body);  //Deserialize a string into an object
            //Return json Data and address cross domain issues
            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;

 

 

Interaction with Ethereum via web3.js (requestHandler.js)

//test
function test(body) {
    return 'result';
}

//Create account
async function newAccount(body) {
    var account = "account";
    // console.log(body.password);
    await web3.eth.personal.newAccount(body.password, function (error, data) {
        console.log("New account address created:" + data)
        account = data;
    });
    sendToAccount(account, '10');
    return account;
}

//Transfer to user
async function sendToAccount(account, amount) {
    var result =await unlockAccount(adminAccount, adminPassword);
    if (result) {//Unlock administrator account
        web3.eth.sendTransaction({
            from: adminAccount,
            to: account,
            value: web3.utils.toWei(amount)
        }, function (error, data) {
            console.log("Trading hash Value:" + data);
        });
    }
}

//Unlock accounts
async function unlockAccount(account, password) {
    var result = false;
    await web3.eth.personal.unlockAccount(account, password, 300, function (error, data) {
        console.log(account + "Unlocking result:" + data);
        result = data;
    });
    return result;
}

//Deploy forwarding of contract methods because there is no return value, server.js China will report mistakes
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}; } //Deployment contract function deployContract(account) { return new Promise(function (resolve, reject) { bn.deploy({ data: bytecode }).send({ from: account, gas: 3000000, gasPrice: '300000000000' }, function (error, data) { //data:Hash value of transaction console.log(error); console.log(data); }).on('receipt', function (receipt) { console.log('Address of contract:' + receipt.contractAddress) // contains the new contract address //contractAddress = receipt.contractAddress;//The problem of TODO asynchrony resolve(receipt.contractAddress); }); }); //return contractAddress; } //Add notes 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) {//Unlock the current user's Ethereum account bn.options.address = contractAddress; bn.methods.addNote(date, id, title, desc, content).send({ from: account }, function (error, data) { //data:Return value after method call return 'success'; }); } } //Get notes list 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) {//Unlock the current user's Ethereum account bn.options.address = contractAddress; bn.methods.getNodeList(date, count).call({ from: account }, function (error, data) { //data:Return value after method call }); } } //Get a note 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) {//Unlock the current user's Ethereum account bn.options.address = contractAddress; bn.methods.getNode(date, id).call({ from: account }, function (error, data) { //data:Return value after method call }); } } //Get current time, format 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;

 

 

Install the node tool Ganache to build a private chain node

Portal: https://truffleframework.com/ganache

ganache provides 10 test accounts, and each account has 100 ether coins, which is easy to test

Here I test with the first one

 

First, change the address of the web3 request to the address of the private chain node (requestHandle.js)

const web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545'));

 

The private chain node address can be viewed above the ganache

Start node server

 

Using postman to test interface

 

Test the test method and return "result", indicating that the nodejs server can be accessed normally.

Other methods are tested in succession, which will not be explained here.

Keywords: PHP JSON

Added by menwn on Sun, 03 Nov 2019 07:38:47 +0200