0

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.

6
  • check if the port is open using netstat cmd
    – Badr Bellaj
    Apr 21, 2018 at 7:46
  • yes it is opened. tcp 0 0 127.0.0.1:8545 0.0.0.0:* LISTEN 1521/geth Apr 21, 2018 at 8:08
  • try 127.0.0.1 instead localhost
    – Badr Bellaj
    Apr 21, 2018 at 8:11
  • did but same error Apr 21, 2018 at 8:16
  • 1
    install metamask and check if it connect to your nodein localhost mode
    – Badr Bellaj
    Apr 21, 2018 at 9:05

1 Answer 1

0

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.