首页
学习
活动
专区
圈层
工具
发布

返回null
EN

Stack Overflow用户
提问于 2018-11-12 10:13:35
回答 2查看 3.4K关注 0票数 0

我正在创建一个react应用程序,它可以与运行在rpcport 8545上的geth一起运行的ethereum私有区块链交互。

因此,我使用web3.js来获取块链上的数据,下面是我的代码:

代码语言:javascript
复制
var Web3 = require('web3');
var web3 = new Web3("http://localhost:8545");

在render()方法中:

代码语言:javascript
复制
console.log(web3.eth.blockNumber);
console.log(Web3.givenProvider);

它应该在浏览器控制台中显示我当前的blockNumber和我正在侦听的端口,但是相反,我得到了未定义的null,这似乎意味着我没有连接到我正在运行的块链。

顺便说一下,我的区块链是用这一行运行的:

代码语言:javascript
复制
geth --datadir ./noeud2 --networkid 100 --port 30301 --rpcport 8545

你知道为什么这不管用吗?

我一直在学习本教程:

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

但对我来说也不管用。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-13 04:39:56

在直接调试您的react代码之前,最好先从一个简单的基于html的应用程序开始,然后尝试查询您的私有Ethereum链。为此,请执行以下步骤

  1. 创建以下index.html文件

index.html

代码语言:javascript
复制
<!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,您可以尝试使用下面的配置来启动您的Ethereum

代码语言:javascript
复制
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

代码语言:javascript
复制
npm install -g ganache-cli

完成后,运行以下命令来启动它:

代码语言:javascript
复制
ganache-cli 

如果你觉得你没有web3,你也可以尝试下面的方法

使用以下命令安装web3.js

代码语言:javascript
复制
npm install ethereum/web3.js — save

现在,您可以尝试连接到刚开始使用Remix的Ganache CLI。

打开http://remix.ethereum.org,单击Run选项卡,然后将环境下拉列表从Javascript更改为Web3提供程序。

点击“OK”,然后指定testrpc/ganache-cli本地主机地址(默认情况下,它是http://localhost:8545)

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

先尝试以上步骤,然后用您的输出进行注释。

票数 1
EN

Stack Overflow用户

发布于 2018-11-12 12:22:13

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53259966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档