首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >通过websockets或HTTP将geth连接到web3.js1.0

通过websockets或HTTP将geth连接到web3.js1.0
EN

Ethereum用户
提问于 2018-01-28 20:16:05
回答 3查看 9.7K关注 0票数 5

我正在构建一个最小的nodeJS应用程序,它应该通过web3.js连接到我的geth节点。我正在跟踪正式web3.js1.0文档,并使用web3 1.0.0-beta.29。

我确实设法通过IPC进行连接,但是HTTP和websockets都失败了--在这两种情况下,我从JS脚本获得了相同的输出,就好像根本没有运行geth一样。任何帮助都将不胜感激。

( 1) HTTP (不工作)

盖斯:

代码语言:javascript
运行
复制
geth syncmode="fast" --cache=4096 --rpc --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,personal"

index.js:

代码语言:javascript
运行
复制
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545'); // same output as with option below
// var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getAccounts(console.log);
console.log("Hello World");

产出:

代码语言:javascript
运行
复制
$ node index.js
Hello World
Error: Invalid JSON RPC response: ""

( 2) websockets (不工作)

盖斯:

代码语言:javascript
运行
复制
geth syncmode="fast" --cache=4096 --ws --wsport 8546 --wsorigins "*" console

index.js:

代码语言:javascript
运行
复制
var Web3 = require('web3');
var web3 = new Web3("ws://localhost:8546"); // same output as with option below
// var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
web3.eth.getAccounts(console.log);
console.log("Hello World");

产出:

代码语言:javascript
运行
复制
$ node index.js
Hello World
connection not open on send()
Error: connection not open

( 3) IPC (works)

geth:(与HTTP相同的开始)

geth syncmode="fast“--cache=4096 --rpcport 8545 --rpccorsdomain "*”--rpcapi "eth,web3,personal“

index.js:

代码语言:javascript
运行
复制
var net = require('net');
var Web3 = require('web3');
var web3 = new Web3('/Users/sebastian/Library/Ethereum/geth.ipc', net); // same output as with option below
// var web3 = new Web3(new Web3.providers.IpcProvider('/Users/sebastian/Library/Ethereum/geth.ipc', net));
web3.eth.getAccounts(console.log);
console.log("Hello World");

产出:

代码语言:javascript
运行
复制
$ node index.js
Hello World
null [ '0x045a6A820FD596a4c1a49732af01E3EF1D6aEb8B' ]
EN

回答 3

Ethereum用户

回答已采纳

发布于 2018-01-29 00:30:08

geth命令行中有一个错误:在同步模式前面漏掉了双破折号。不确定原因,但它似乎阻止geth启动HTTP侦听器。

票数 2
EN

Ethereum用户

发布于 2018-10-17 04:19:30

基本上,需要在--wsorigins "*"命令中声明选项geth,以便通过websocket providerhttp provider连接到节点。

在您的示例中,您在syncmode前面缺少了双破折号,添加了双重破折号或删除了syncmode解决了这个问题。

另外,根据https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options一文,

--来源值:接受websockets请求的来源

希望能帮上忙。

票数 1
EN

Ethereum用户

发布于 2022-05-24 06:21:55

如果有人正在使用Geth 1.10.17-stable-25c9b49f,那么命令行选项已经发生了一些变化。

为了启用HTTP服务器,我们现在使用--http标志。现在,使用以下代码将实现同样的结果:geth --http --http.corsdomain "*" --http.api personal,eth,web3

代码语言:javascript
运行
复制
// Node.js app
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
web3.eth.getAccounts(console.log);
票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/37776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档