[Ethereum] connecting geth to web3.js 1.0 via websockets or HTTP

go-ethereumipcjson-rpcweb3jswebsocket

I am building a minimal nodeJS application that should connect via web3.js to my geth node. I am following the official web3.js1.0 documentation and I am using web3 1.0.0-beta.29.

I do manage to connect via IPC but both HTTP and websockets fail – in both cases I get the same output from my JS script as if there was no geth running at all. Any help would be appreciated.

1) HTTP (not working)

geth:

geth syncmode="fast" --cache=4096 --rpc --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,personal"

index.js:

var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545'); // same output as with option below
// var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getAccounts(console.log);
console.log("Hello World");

output:

$ node index.js
Hello World
Error: Invalid JSON RPC response: ""

2) websockets (not working)

geth:

geth syncmode="fast" --cache=4096 --ws --wsport 8546 --wsorigins "*" console

index.js:

var Web3 = require('web3');
var web3 = new Web3("ws://localhost:8546"); // same output as with option below
// var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
web3.eth.getAccounts(console.log);
console.log("Hello World");

output:

$ node index.js
Hello World
connection not open on send()
Error: connection not open

3) IPC (works)

geth: (same start as for HTTP)

geth syncmode="fast" –cache=4096 –rpc –rpcport 8545 –rpccorsdomain "*" –rpcapi "eth,web3,personal"

index.js:

var net = require('net');
var Web3 = require('web3');
var web3 = new Web3('/Users/sebastian/Library/Ethereum/geth.ipc', net); // same output as with option below
// var web3 = new Web3(new Web3.providers.IpcProvider('/Users/sebastian/Library/Ethereum/geth.ipc', net));
web3.eth.getAccounts(console.log);
console.log("Hello World");

output:

$ node index.js
Hello World
null [ '0x045a6A820FD596a4c1a49732af01E3EF1D6aEb8B' ]

Best Answer

There is a typo in geth command line: you miss double dash in front of syncmode. Not sure why, but it seems to prevent geth from launching HTTP RPC listener.