我正在创建一个react应用程序,该应用程序与rpcport 8545上使用geth运行的以太坊私有区块链进行交互。
因此,我使用web3.js在我的区块链上获取数据,下面是我的代码:
var Web3 = require('web3');
var web3 = new Web3("http://localhost:8545");
在render((方法中:
console.log(web3.eth.blockNumber);
console.log(Web3.givenProvider);
它应该在浏览器控制台中显示我当前的blockNumber和我正在监听的端口,但我得到了未定义和null,这似乎意味着我没有连接到我正在运行的区块链。
顺便说一句,我的区块链是用这条线运行的:
geth --datadir ./noeud2 --networkid 100 --port 30301 --rpcport 8545
你知道为什么不起作用吗?
我一直在遵循这个教程:
https://www.codeooze.com/blockchain/ethereum-block-explorer-react-02/
但这对我也不起作用。
在直接调试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 ethereum区块链时出现问题
使用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,单击Run选项卡,然后将Environment下拉列表从Javascript VM更改为Web3 Provider。
点击"OK",然后指定testrpc/ganache cli localhost地址(默认情况下http://localhost:8545)
现在,我们不再在Remix中的Javascript VM中进行部署和测试,而是在您的计算机上使用Ganache CLI客户端。
请先尝试以上步骤,然后用您的输出进行反馈。
web3
的初始化应该是这样的:var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));