web3js – How to Connect to the Ropsten Test-net Using web3js

infuraropstentestnetsweb3js

I want to connect to the Ropsten test-net:

    // Is there is an injected web3 instance?
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      // If no injected web3 instance is detected, fallback to the TestRPC.
      App.web3Provider = new web3.providers.HttpProvider('http://localhost:8545');
      web3 = new Web3(App.web3Provider);
    }

I have http://localhost:8545 in this code. How do I connect to Ropsten instead of http://localhost:8545?

Best Answer

You can either run a local node and specify your chain using --chain ropsten when starting geth/parity and connect to localhost once sync is completed or you can connect to infura.io:

var web3 = new Web3(new Web3.providers.HttpProvider(
    'https://ropsten.infura.io/v3/[infura_project_id]'
));