I'm creating a react-app that interacts with an ethereum private blockchain running with geth on rpcport 8545.
I am thus using web3.js to fetch data on my blockchain, and here's my code:
var Web3 = require('web3');
var web3 = new Web3("http://localhost:8545");
and in the render() method:
console.log(web3.eth.blockNumber);
console.log(Web3.givenProvider);
It should display in the browser console my current blockNumber and on which port I'm listening, but instead I get undefined and null, which seems to mean that I'm not connected to my running blockchain.
btw my blockchain is running with this line:
geth --datadir ./noeud2 --networkid 100 --port 30301 --rpcport 8545
Do you know why this isn't working?
I have been following this tutorial:
https://www.codeooze.com/blockchain/ethereum-block-explorer-react-02/
But it does not work for me either.
Before directly getting into debugging your react code, it is better to start with a simple html based application and try to query your private Ethereum chain. For that follow the below steps
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>
With Geth you can try with the below configuration to start your Ethereum
geth --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --nodiscover --networkid "$NETWORKID" --datadir ~/.ethereum_experiment --genesis ~/genesis_block.json
Or else, you can try using Ganache CLI (TestRPC) instead of Geth as well
Ganache CLI can be installed using the following command
npm install -g ganache-cli
Once finished, run the following command to start it:
ganache-cli
You can also try the following as well if you feel you don't have the web3
Install web3.js using the following command
npm install ethereum/web3.js — save
Now you can try connecting to the Ganache CLI you just started by using the Remix IDE first.
Open http://remix.ethereum.org, click on the Run tab, and then change the Environment drop-down from Javascript VM to Web3 Provider.
Hit “OK” and then specify the testrpc/ganache-cli localhost address (by default, it’s http://localhost:8545)
Now instead of deploying and testing in the Javascript VM in the Remix, we’re now using the Ganache CLI client on your computer.
Try with the above steps first and comment back with your outputs.