How to connect web3js to mainnet or testnet?

ahmed_chahmed_ch Posts: 7Member
Hello, I want to make a web app which interacts with a contract on testnet/mainnet. I can see in the documentation that the local port to web3js to connect to a local running ethereum instance/simulation:

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

But I want to connect it to the testnet or mainnet. Is it possible to do that without actually hosting a real node(test or main) via metamask as a full Ethereum node.

Answers

  • o0ragman0oo0ragman0o Posts: 1,213Member, Moderator mod
    Looks like the standard provider set up is now...
    http://web3js.readthedocs.io/en/1.0/web3.html
    var web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider("ws://localhost:8546"));
    If you're running MetaMask, then it connects through to Conensys run nodes via the Web3.givenProvider
  • aminnagpureaminnagpure Posts: 6Member
    edited March 21
    install parity, it works

    if u install metamask, u will have to install testrpc and run it as a local node
  • ahmed_chahmed_ch Posts: 7Member
    edited March 27

    install parity, it works

    if u install metamask, u will have to install testrpc and run it as a local node

    Thanks, but actually I want to use testnet not a local node.
  • ahmed_chahmed_ch Posts: 7Member
    edited March 27

    Looks like the standard provider set up is now...
    http://web3js.readthedocs.io/en/1.0/web3.html

    var web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider("ws://localhost:8546"));
    If you're running MetaMask, then it connects through to Conensys run nodes via the Web3.givenProvider
    Thanks for your answer,After I have installed Metamask and joined the Ropsten testnet via Mist, and in my JS file, i initialized the provider:
    if (typeof web3 !== 'undefined') {
    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);
    } else {
    console.log('No web3? You should consider trying MetaMask!')
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }
    I got this error:
    Uncaught Error: CONNECTION ERROR: Couldn't connect to node http://localhost:8545.
    Post edited by o0ragman0o on
  • aminnagpureaminnagpure Posts: 6Member
    you got to run a node testrpc, i saw some program which runs a testnetwork on your machine and then you connect to that testnetwork with web3
Sign In or Register to comment.