我正在构建一个最小的nodeJS应用程序,它应该通过web3.js连接到我的geth节点。我正在跟踪正式web3.js1.0文档,并使用web3 1.0.0-beta.29。
我确实设法通过IPC进行连接,但是HTTP和websockets都失败了--在这两种情况下,我从JS脚本获得了相同的输出,就好像根本没有运行geth一样。任何帮助都将不胜感激。
( 1) HTTP (不工作)
盖斯:
geth syncmode="fast" --cache=4096 --rpc --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,personal"
index.js:
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");
产出:
$ node index.js
Hello World
Error: Invalid JSON RPC response: ""
( 2) websockets (不工作)
盖斯:
geth syncmode="fast" --cache=4096 --ws --wsport 8546 --wsorigins "*" console
index.js:
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");
产出:
$ 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:
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");
产出:
$ node index.js
Hello World
null [ '0x045a6A820FD596a4c1a49732af01E3EF1D6aEb8B' ]
发布于 2018-01-29 00:30:08
geth命令行中有一个错误:在同步模式前面漏掉了双破折号。不确定原因,但它似乎阻止geth启动HTTP侦听器。
发布于 2018-10-17 04:19:30
基本上,需要在--wsorigins "*"
命令中声明选项geth
,以便通过websocket provider
或http provider
连接到节点。
在您的示例中,您在syncmode
前面缺少了双破折号,添加了双重破折号或删除了syncmode
解决了这个问题。
另外,根据https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options一文,
--来源值:接受websockets请求的来源
希望能帮上忙。
发布于 2022-05-24 06:21:55
如果有人正在使用Geth 1.10.17-stable-25c9b49f
,那么命令行选项已经发生了一些变化。
为了启用HTTP
服务器,我们现在使用--http
标志。现在,使用以下代码将实现同样的结果:geth --http --http.corsdomain "*" --http.api personal,eth,web3
// Node.js app
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
web3.eth.getAccounts(console.log);
https://ethereum.stackexchange.com/questions/37776
复制相似问题