I want to interact with a smart contract using web3js. Every example will start with following
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
// or
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
I don't understand the use of Web3.providers.HttpProvider('Address'). My Guess: So when establishing a private network every node should give a different rpcport which identifies it and so it connects to the network. Am I wrong? For example, the above code is used in Frontend for a website in order to connect frontend and deploy a contract in Ethereum Private Network. So the frontend code must be generic which means it should not add specific Ethereum node address in its code. Then what is the use of Web3.providers.HttpProvider('Address')?
It has nothing to do with using a private vs public blockchain.
You need to give your client a way to connect to the blockchain. Specifically, the web3js library requires Provider
object that includes the connection protocol and the address/port of the node you're going to connect to.
Web3js support 3 different providers: HttpProvider
, WebsocketProvider
, and IpcProvider
. Both HTTP and WS require the address of the node (IPC uses a file). The address itself will be localhost if you're running a peer node on your client (ie, using Parity or Geth). If you're using a centralized provider like Infura, you would use https://mainnet.infura.io/API_KEY
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With