[Ethereum] How to connect web3js to mainnet or testnet

contract-invocationweb3js

It might be a very basic question. But here's what I want to achieve:

I want to make a web app which interacts with a contract on testnet/mainnet.
I can see in the documentation that you have to provide 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)?

And if the only way to do this is by running an actual node on local computer, then what is the best way to connect to it with web3? I read somewhere that RPC is not that secure.

Please guide me on these noobie questions.

Thanks in advance!

Best Answer

web3js will connect to your ethereum local or distant node(its is obvious while you need your account to send transactions). So in order to use the mainnet or testnet configure your ethereum client to do so e.g geth --testnet.

Concerning the security : you have to protect your node against incoming connection to the RPC port by configuring your Firewall to allow only the connections originating from the local computer or from a white listed IPs.

read : https://blog.ethereum.org/2015/08/29/security-alert-insecurely-configured-geth-can-make-funds-remotely-accessible/