在直接调试你的 react 代码之前,最好先从一个简单的基于 html 的应用程序开始,然后尝试查询你的私有以太坊链。为此,请按照以下步骤操作
- 创建以下 index.html 文件
index.html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<title>Document</title>
//provide the location of web3 file
<script src=”./node_modules/web3/dist/web3.min.js”></script>
</head>
<body>
<div class=”container”>
<h1>Given below Ethereum address</h1>
<div id=”AccountAddress”></div>
<script src=”https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
if (typeof web3 !== ‘undefined’)
{
web3 = new Web3(web3.currentProvider);
}
else
{
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider(“http://localhost:8545”));
}
$(“#AccountAddress”).html(web3.eth.accounts[0]);
</script>
</body>
</html>
- 当您在浏览器中打开 index.html 文件时,如果未显示第一个帐户地址,则表示您在连接到刚刚拆分的 geth 以太坊区块链时出现问题。
使用 Geth,您可以尝试使用以下配置来启动您的以太坊
geth --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --nodiscover --networkid "$NETWORKID" --datadir ~/.ethereum_experiment --genesis ~/genesis_block.json
或者,您也可以尝试使用 Ganache CLI (TestRPC) 而不是 Geth
Ganache CLI 可以使用以下命令安装
npm install -g ganache-cli
完成后,运行以下命令启动它:
ganache-cli
如果你觉得没有web3也可以试试下面的方法
使用以下命令安装 web3.js
npm install ethereum/web3.js — save
现在您可以尝试先使用 Remix IDE 连接到刚启动的 Ganache CLI。
打开http://remix.ethereum.org,点击运行选项卡,然后将环境下拉菜单从Javascript VM更改为Web3 Provider。
点击“OK”,然后指定 testrpc/ganache-cli localhost 地址(默认为http://localhost:8545)
现在,我们不再在 Remix 中的 Javascript VM 中进行部署和测试,而是在您的计算机上使用 Ganache CLI 客户端。
先尝试上述步骤,然后对您的输出进行评论。