You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Node.js对接Hyperledger Fabric+Composer多组织网络端到端教程

端到端Node.js对接Hyperledger Fabric Composer网络教程

咱先明确前提:你已经搞定了本地Fabric网络部署,Composer业务网络也已经上链,手里还有生成好的业务卡片(.card文件)——接下来的步骤完全贴合你的场景,一步步来:

1. 先把依赖装到位

Node.js应用要对接Composer,得先装两个核心包:

npm install composer-client composer-common --save

如果要调用Composer REST Server的API,还可以装个axios方便发请求:

npm install axios --save

2. 钱包管理:存放你的业务卡片

钱包是Node.js应用用来存储和管理业务卡片的地方,本地开发最常用的是FileSystemWallet(文件系统钱包),直接存在项目目录里就行。

先写代码创建钱包:

const { FileSystemWallet } = require('composer-client');
const path = require('path');

// 把钱包放在项目根目录的wallet文件夹下
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);

然后把你手里的.card文件导入到这个钱包里——用Composer CLI命令最省事:

composer card import -f admin@my-business-network.card --wallet-type filesystem --wallet-path ./wallet

这里的admin@my-business-network.card是你的卡片文件名,替换成自己的就行。

3. 用卡片连接到业务网络

现在钱包里有卡片了,接下来写代码连接到Fabric网络:

const { BusinessNetworkConnection } = require('composer-client');

async function connectToNetwork() {
    // 卡片名称,就是你导入时的名字,比如admin@my-business-network
    const cardName = 'admin@my-business-network';
    
    // 先检查钱包里有没有这张卡
    const cardExists = await wallet.exists(cardName);
    if (!cardExists) {
        console.log(`糟了,卡片${cardName}不在钱包里,先去导入哦!`);
        return null;
    }
    
    // 用卡片建立网络连接
    const businessNetworkConnection = new BusinessNetworkConnection();
    try {
        await businessNetworkConnection.connect(cardName);
        console.log('成功连上业务网络啦!');
        return businessNetworkConnection;
    } catch (error) {
        console.error('连接失败:', error);
        return null;
    }
}

4. 执行业务操作:查询资产/提交交易

连接上网络后,就可以操作区块链上的数据了,举两个常用例子:

查询资产

async function queryAllAssets(businessNetworkConnection) {
    if (!businessNetworkConnection) return;
    
    // 获取对应资产的注册表
    const assetRegistry = await businessNetworkConnection.getAssetRegistry('org.example.mynetwork.MyAsset');
    // 查询所有资产
    const allAssets = await assetRegistry.getAll();
    
    console.log('查到的资产列表:', allAssets);
    return allAssets;
}

这里的org.example.mynetwork.MyAsset要替换成你自己业务网络里的资产类型。

提交交易

async function submitSampleTransaction(businessNetworkConnection) {
    if (!businessNetworkConnection) return;
    
    // 构建交易对象,参数要和你业务网络里的交易定义匹配
    const transaction = businessNetworkConnection.buildTransaction('org.example.mynetwork.UpdateAssetValue', {
        asset: 'resource:org.example.mynetwork.MyAsset#ASSET001',
        newValue: '更新后的新值'
    });
    
    try {
        await businessNetworkConnection.submitTransaction(transaction);
        console.log('交易提交成功!');
    } catch (error) {
        console.error('交易失败:', error);
    }
}

5. 基于Composer REST Server开发Node.js应用

如果你想直接用Composer生成的REST API来开发,步骤更简单:

先启动REST Server

composer-rest-server -c admin@my-business-network -n never -w true

参数说明:-c指定用哪个卡片连接,-n never禁用自动更新,-w true启用CORS方便本地调试。

Node.js里调用REST API

用axios发请求就行,比如查询资产、创建资产:

const axios = require('axios');

// 查询所有资产
async function getAssetsViaREST() {
    try {
        const response = await axios.get('http://localhost:3000/api/MyAsset');
        console.log('通过REST API拿到的资产:', response.data);
        return response.data;
    } catch (error) {
        console.error('REST请求失败:', error);
    }
}

// 创建新资产
async function createAssetViaREST() {
    const newAsset = {
        $class: 'org.example.mynetwork.MyAsset',
        assetId: 'ASSET002',
        value: '初始值'
    };
    
    try {
        const response = await axios.post('http://localhost:3000/api/MyAsset', newAsset);
        console.log('资产创建成功:', response.data);
    } catch (error) {
        console.error('创建资产失败:', error);
    }
}

6. 参与者身份的注册与绑定(进阶)

如果需要给新参与者创建身份,绑定到区块链上的参与者对象,再生成新卡片,代码示例:

const { X509WalletMixin } = require('composer-client');

async function registerNewParticipant(businessNetworkConnection) {
    if (!businessNetworkConnection) return;
    
    // 先获取参与者注册表,假设你已经在链上创建了这个参与者
    const participantRegistry = await businessNetworkConnection.getParticipantRegistry('org.example.mynetwork.Customer');
    const customer = await participantRegistry.get('CUST001');
    
    // 给这个参与者发行身份
    const identity = await businessNetworkConnection.issueIdentity(
        `org.example.mynetwork.Customer#CUST001`, 
        'customer001@my-business-network'
    );
    
    // 把新身份导入钱包
    await wallet.import(
        'customer001@my-business-network', 
        X509WalletMixin.createIdentity('my-business-network', identity.userID, identity.userSecret)
    );
    
    console.log('新参与者身份已注册并导入钱包!');
}

几个注意事项

  • Node.js版本建议用8.x或10.x,高版本Node可能和Composer不兼容;
  • 卡片名称要和导入时完全一致,大小写都不能错;
  • 如果连接失败,先检查Fabric网络是否正常运行,卡片是否有效。

内容的提问来源于stack exchange,提问作者Dheeraj Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:18:16