[Ethereum] CONNECTION ERROR: Couldn’t connect to node http://localhost:8545

geth-debugginggo-ethereumjson-rpcweb3js

I have started geth using below:

geth --rpc --rpccorsdomain * --rpcport 8545 --rpcapi personal,web3,eth,net

and this is my web3.js code:

<script src="/bower_components/web3/dist/web3.min.js"></script>
<script type="text/javascript">
    function send() {
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        }
        if(!web3.isConnected()) {
            console.log('not-connected');
        } else {
           console.log('connected');
        }
    }
</script>

first console.log said "not-connected" and got an error: Error: CONNECTION ERROR: Couldn't connect to node http://localhost:8545.

Best Answer

Just a small error of scopes. Your web3 variable goes out of scope as soon as it is declared.

<script src="/bower_components/web3/dist/web3.min.js"></script>
<script type="text/javascript">
    var web3;
    function send() {
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        }
        if(!web3.isConnected()) {
            console.log('not-connected');
        } else {
           console.log('connected');
        }
    }
</script>

Note that I have declared var web3 explicitly outside the function

Related Topic