web3.js错误合集

在web3.js的新版本中,eth.filter已被弃用,应使用eth.subscribe代替。然而,subscribe需要WebSocket协议支持。错误提示表明HTTP提供程序不支持订阅。要解决此问题,需要使用WebsocketProvider连接到本地节点,例如通过geth的WebSocket端口。另外,高版本的web3可能引起构造函数错误,降级到1.10.0版本可以解决问题。

错误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就不存在这个问题了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值