Web3.givenProvider返回null

时间:2018-11-12 10:13:35

标签: reactjs blockchain ethereum web3 geth

我正在创建一个与rpcport 8545上运行geth的以太坊私有区块链交互的react-app。

因此,我正在使用web3.js在我的区块链上获取数据,这是我的代码:

var Web3 = require('web3');
var web3 = new Web3("http://localhost:8545");

以及在render()方法中:

console.log(web3.eth.blockNumber);
console.log(Web3.givenProvider);

它应该在浏览器控制台中显示我当前的blockNumber并在我正在监听的端口上显示,但是我却得到了undefined和null,这似乎意味着我没有连接到我正在运行的区块链。

顺便说一下,我的区块链正在运行以下代码:

geth --datadir ./noeud2 --networkid 100 --port 30301 --rpcport 8545

您知道为什么这不起作用吗?

我一直在关注本教程:

https://www.codeooze.com/blockchain/ethereum-block-explorer-react-02/

但这对我也不起作用。

2 个答案:

答案 0 :(得分:1)

在直接调试您的React代码之前,最好从一个简单的基于html的应用程序开始,然后尝试查询您的私有以太坊链。为此,请按照以下步骤操作

  1. 创建以下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>
  1. 在浏览器中打开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。

点击“确定”,然后指定testrpc / ganache-cli本地主机地址(默认为http://localhost:8545

现在,我们不再在Remix中的Javascript VM中进行部署和测试,而是在您的计算机上使用Ganache CLI客户端。

首先尝试执行上述步骤,然后使用输出进行注释。

答案 1 :(得分:0)

web3的初始化应如下所示: var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));