Hello everyone can you please help me to solve this error : The conditions I want to run: I use NodeJs with Web3.js to find the balance of the account address in Blockchain using 'getBalance()' function. My code is run perfectly on 'localhost' and I get the correct account balance .For checking the result I return the balance using express route to the webpage. But the problem is.. when we upload the program on the server it can't get balance It gets error(i.e catch block is executed ) and return '{}' empty parenthesis.
For solving this error I try many approaches like:
- Changing web3 provider.
- Changing different address.
- and I also use web3 'privateKeyToAccount(privateKey)' function for getting account address using private key and I am geting excited that this function is executed successfully and give a correct address. But 'getBalance' function is not excuted correctly.
- And I also use transaction function but it is also not run correctly.
- I search many documentations and tutorials but I not get solution.
- versions I use for nodejs 'v18.14.1' and for web3 '1.8.2'.
Here is my code:
const Web3 = require('web3');
const express = require('express');
const web3 = new Web3('https://mainnet.infura.io/v3/<MYINFURAKEY>');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
web3.eth.getBalance("0x7830c87C02e56AFf27FA8Ab1241711331FA86F43").then(balance => {
res.send(balance);
})
.catch(error => {
res.send(error);
});
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
I try to get balance of account address using nodejs and web3. For ofline it executed correctly but when we upload on server it not execute successfully it gets error.
After spending more time to solve this error I found small code related to this.
const Web3 = require('web3');
const express = require('express');
web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/e365c07adf544980a71258eca29fceed'));
const app = express();
app.use(express.json());
app.get('/',(req, res) => {
web3.eth.net.isListening()
.then(() => res.send('is connected'))
.catch(e => res.send('Wow. Something went wrong: '+ e));
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
This code gives the same error
{Wow. Something went wrong: Error: CONNECTION ERROR: Couldn't connect to node https://mainnet.infura.io/v3/e365c07adf544980a71258eca29fceed.}
for online but offline it works fine.