官术网_书友最值得收藏!

  • Hyperledger Cookbook
  • Xun (Brian) Wu Chuanfeng Zhang Andrew Zhang
  • 320字
  • 2021-06-24 14:59:43

Writing Node.js sever-side code

We have now set up the client environment. We should be able to connect to the remote Fabric network and trigger the chaincode API. In our Node.js app, create the app.js file. This file will act as a connector to create a new gateway to connect to our peer node. It also creates a new filesystem-based wallet for managing identities. Once we have connected to the peer node, the function in app.js can find a contract through the channel and then submit the specified transaction. To do this, follow these steps:

  1. Create the wallet file:
async function ship() {
try {
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
..
}
  1. The wallet file needs to make sure the user exists by using the wallet.exist API:
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}
  1. Connect to blockchain through gateway, bypassing the wallet and identity information. Once connected to the network successfully, get the assetmgr contract from the network:
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('assetmgr');

  1. Submit a transaction to invoke the chaincode function:
// Submit the specified transaction.
await contract.submitTransaction("Ship", "100", "OEM deliver ipad to school", "New Jersey");
  1. Disconnect from gateway and return to the client caller. To do this, follow the code:
// Disconnect from the gateway.
await gateway.disconnect();
With node.js, you need set up your node.js server listen, of course.
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
主站蜘蛛池模板: 天长市| 施秉县| 万荣县| 盐亭县| 商南县| 驻马店市| 静宁县| 泸定县| 石城县| 丹阳市| 和田市| 建宁县| 吴忠市| 莱州市| 兴国县| 都兰县| 阿城市| 西林县| 阜城县| 龙山县| 宜君县| 潜山县| 许昌市| 德昌县| 新竹县| 依兰县| 邯郸市| 太谷县| 南平市| 射阳县| 大庆市| 商水县| 宜城市| 中牟县| 遂昌县| 浙江省| 紫云| 阿拉善盟| 兴业县| 什邡市| 河池市|