简体   繁体   中英

how to return web3 instance from nodejs to ui

I want to return a web3 instance that contains provider object. I want to return that object to UI so that i can use that web3 instance in UI. Is this possible to achieve? I tried converting the web3 to JSON.stringify(web3) but throwing error cannot convert circular objects to string.

here is my nodejs code

    const provider = new HDWalletProvider(
    'dress steel phrase album average asd dd room exile web eree cause',
    'https://rinkeby.infura.io/I7P2ErGiQjuq4jNp41OE',
  );

  web3 = new Web3(provider);

I would like to return web3 instance to UI from node like this

app.get('/getWeb3', async (req, res) => {

  console.log('web3 instance', web3);

  res.json( JSON.stringify(web3)); // this is throwing error.
})

I have tried using third party libraries to convert object to json like warp library but still facing issues. Any suggestions will be helpful to me. Thanks

You can't send a web3 instance, that doesn't make much sense, since you can get a web3 instance directly on the client side.

Usually on the client side, you use Metamask , that will allow you to interact with the Ethereum network without running a full node.

client side

if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  // set the provider you want from Web3.providers
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
// Interact with your contract
const Contract = web3.eth.contract(ABI);
const contract = Contract.at('address'); 

contract.someMethod((err, res) => console.log(res));

Now the user will interact with the Ethereum network, using it's own address and keys, instead of using your private keys, which is what you were trying to do.

The web3 instance on the server must remain private, and not be exposed to the client.

Instead of trying to send the instance to the client, why don't you tell us what are you trying to do with that instance, which is the actual question that needs to be solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM