繁体   English   中英

如何将web3实例从nodejs返回到ui

[英]how to return web3 instance from nodejs to ui

我想返回一个包含提供者对象的web3实例。 我想将该对象返回到UI,以便可以在UI中使用该web3实例。 这有可能实现吗? 我尝试将web3转换为JSON.stringify(web3),但抛出错误无法将圆形对象转换为字符串。

这是我的nodejs代码

    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);

我想从这样的节点将web3实例返回到UI

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

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

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

我曾尝试使用第三方库将对象转换为warp库之类的json,但仍然面临问题。 任何建议对我都会有帮助。 谢谢

您无法发送web3实例,这没有多大意义,因为您可以直接在客户端获得一个web3实例。

通常在客户端,您使用Metamask ,这将允许您与以太坊网络进行交互,而无需运行完整的节点。

客户端

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));

现在用户将使用其自己的地址和密钥与以太坊网络进行交互,而不是使用您试图这样做的私有密钥。

服务器上的web3实例必须保持私有状态,并且不向客户端公开。

与其尝试将实例发送给客户端,不如不告诉我们您打算如何处理该实例,这是需要解决的实际问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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