Web3js Server-Side Connection Issues with Ganache – Troubleshooting Guide

ganachejavascriptnodejsweb3js

I need to create server in nodejs that will create transaction to blockchain and i have trouble to connect my nodejs app with ganache. Look at my code:

const Web3 = require('web3');
var web3 = new Web3.providers.HttpProvider('http://localhost:7545'); // ganache address
console.log(web3.eth.accounts); // should print 10 accounts but its error like eth is undefined

In my dependencies

"web3": "^0.20.2"

Using this code on client-side works, what am i missing?

Best Answer

This line is wrong:

var web3 = new Web3.providers.HttpProvider('http://localhost:7545');

You're instantiating a provider instead of instantiating Web3. It should be this:

var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
Related Topic