在网络浏览器中连接到以太坊节点

Connecting to Ethereum node in web browser

我收到这个错误:

CONNECTION ERROR: Couldn't connect to node http://localhost:8545, is it running?

我目前正在尝试将 Meteor 应用程序与私有测试网络上的节点一起使用。我也在真实网络的真实节点上尝试过 运行 它。我可以访问 web3.eth 对象,但我似乎无法连接到我的节点!太令人沮丧了!

我的应用在 http://localhost:3000

上运行

我在启动我的节点时尝试了以下方法,但它们都不起作用(它们启动正常,但我无法通过浏览器连接到它们):

geth --networkid 8545 --genesis ~/genesis_block.json --datadir ~/.ethereum_experiment console
geth --rpccorsdomain "*" --rpc --networkid 8545 --minerthreads "1" --datadir ~/.ethereum_experiment --mine

这是我用来在浏览器控制台中设置提供程序的方法:

web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));

我想我在尝试 运行 VM 中的 geth 时遇到了同样的错误。在那种情况下,问题出在 RPC 仅侦听本地主机。使用 --rpcaddr "0.0.0.0" 将其绑定到所有地址解决了问题:

geth --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --nodiscover --networkid "$NETWORKID" --datadir ~/.ethereum_experiment --genesis ~/genesis_block.json

这里要注意的重要一点是,使用这样的配置,如果端口不在专用网络上或不受防火墙保护,则端口将对来自外部世界的连接开放。

您还可以通过尝试使用 telnet 连接来检查 RPC 端口是否打开:

telnet localhost 8545

一个简单的解决方案是使用像 Alchemy 或 Infura 这样的节点提供商!

https://docs.alchemy.com/alchemy/introduction/getting-started

  1. 通过注册帐户并创建应用程序制作炼金术钥匙

  2. 用这样的东西替换你的 web3 设置:

const { createAlchemyWeb3 } = require("@alch/alchemy-web3"); // Using HTTPS const web3 = createAlchemyWeb3("https://eth-mainnet.alchemyapi.io/<api-key>");

您可以使用来自这些节点提供商之一的免费节点,避免自己维护节点的麻烦。