错误1:使用web3.eth.filter报错:Uncaught TypeError: web3.eth.filter is not a function
在web1.10以上的版本中, web3.eth.filter 方法已被弃用,并且不再可用。 取而代之的是使用 web3.eth.subscribe 方法来实现类似的功能。
var subscription = web3.eth.subscribe('newBlockHeaders', function(error, result){
if (!error) {
console.log(result);
}
});
// 取消订阅
subscription.unsubscribe(function(error, success){
if(success)
console.log('取消订阅成功');
});
错误2:subscribe订阅事件报错,得用websocket协议
Error: The current provider doesn't support subscriptions: HttpProvider
at Subscription.subscribe
pub / sub不能通过HTTP获得。但是,您可以通过WS使用它。因此,您引用的文档不是100%错误,它只是省略了代码的提供程序部分。
尝试使用网络套接字连接启动节点(geth --ws --wsport 8545 ...,假设您使用的是geth),并更改为WebsocketProvider。
var Web3 = require("web3");
var ether_port = 'ws://localhost:8545'
var web3 = new Web3(new Web3.providers.WebsocketProvider(ether_port));
web3.eth.subscribe("pendingTransactions"
, function(err, result){
if (err){ console.log(err) }
else { console.log("result: ", result) }
});
错误3:引入web3报错
UncaughtTypeError: Web3.providers.HttpProvider is not a constructor。
引入web3报错:
const Web3 = require('web3');
const web3 = new Web3('http://localhost:8545');
报错如下:UncaughtTypeError: Web3.providers.HttpProvider is not a constructor。
问题是,我的web3版本太高了:4.0.2,我降级到1.10.0就不存在这个问题了
在web3.js的新版本中,eth.filter已被弃用,应使用eth.subscribe代替。然而,subscribe需要WebSocket协议支持。错误提示表明HTTP提供程序不支持订阅。要解决此问题,需要使用WebsocketProvider连接到本地节点,例如通过geth的WebSocket端口。另外,高版本的web3可能引起构造函数错误,降级到1.10.0版本可以解决问题。
1510

被折叠的 条评论
为什么被折叠?



