[Ethereum] web3 not connecting to Infura / Rinkeby Testnet

blockchaininfurarinkebyweb3js

I've successfully deployed my Smart-Contract to the Rinkeby TestNet via Remix.
Everything works perfectly from within Remix.

But when I try to get my web DApp to fire methods in my Smart-Contract – nothing's working.

Here's my code for integrating infura to my DApp:

// WEB3 SET-UP:
if(typeof(web3) !== 'undefined') {
    console.log("Web3 provider found! Current Provider is WORKING!");
    web3 = new Web3(web3.currentProvider);
}
else {
    console.log("NO Web3 provider found!  Gonna set one up...");
    // This is NOT working:
    web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/<MY API KEY>"));

    // This is the code I was using to connect to localhost - as provided by Ganache
    // which IS working perfectly well:
    //web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
    console.log("OK, NOW we DO have a PROVIDER --> HttpProvider = ", web3.providers.HttpProvider);   
} 

Of note:
-I did update my Contract's Address in my js code to reflect its new address on Rinkeby, so I know that's not the issue.
-The only thing that's different about this code from the version that was working is the HttpProvider. When its set to localhost: 8545 (provide by running Ganache) everything is fine. Its the switching to rinkeby.infura.io/<MY API KEY> that breaks things.

Best Answer

I'm not sure why (because I'm a noob) but when I do

var web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/mykey"));

without the checks, it works somehow, but only with MetaMask installed. When I try it with any other web3 ready browser it just doesn't work. Really confused!

Answering because I can't yet comment and it is a working solution at least for me.

Related Topic